用Sockets接收和转换数字和字符串数据
2024-07-21 02:23:37
供稿:网友
 
多时候远程系统在执行并发任务的时候,会把它接收到数据的长度以数字的形式发送出去。但用socket发送和接收数字型数据的时候,要考虑到一个问题:要根据网络另一端机器的类型转换数据。尤其需要知道怎样把要发送的数据格式(网络格式)从本地机器的格式(主机格式)转换成为行业标准格式。
 使用ipaddress.networktohostorder可以把数据从网络规则转换为主机格式,下面的receiveheader函数说明了它的用法,receiveheader函数实现过程如下:
1 用socket.receive从远程机器接收数据。 
2 验证接收到的字节数是4。
3 socket.receive返回一个字节型数组,bitconvert.toint32把它转换成数字型数值。
4 最后,ipaddress.networktohostorder把长数值转换为主机格式。
public int receiveheader(socket socket)
{
 int datasize = -1; // error
 byte [] buffer = new byte[4];
 int bytesread = socket.receive(buffer, 4,
 system.net.sockets.socketflags.none);
 if (4 == bytesread)
 {
 datasize = bitconverter.toint32(buffer, 0);
 datasize = ipaddress.networktohostorder(datasize);
 }
 else // error condition
 return datasize;
}
 下面再来看一下怎样用多线程读取的方法为每个字符串都建立连接,从远程机器接收字符串型数据。在这种情况下,要把字节型数据转换成string型对象。你可以根据需要用asciiencoding或unicodeencoding类进行转换。receivedetail函数按以下步骤实现(此函数必须在receiveheader后调用,因为datasize的值是从receiveheader中得到的。)
1 在while循环中调用socket.receive,直到无返回值为止。数据被读入一个字节型数组。
2 建立一个asciiencoding对象。
3 调用asciiencoding.getstring把字节型数组转换成string对象,然后把它和先前读入的数据连接。
public string receivedetail(socket socket, byte[] buffer,
 int datasize)
{
 string response = "";
 int bytesreceived = 0;
 int totalbytesreceived = 0;
 while (0 < (bytesreceived = 
 socket.receive(buffer, (datasize - totalbytesreceived),
 socketflags.none)))
 {
 totalbytesreceived += bytesreceived;
 asciiencoding encoding = new asciiencoding();
 response += encoding.getstring(buffer, 0, bytesreceived);
 }
 return response;
}