用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;
}