Receive and convert numbers and string data with Sockets

zhaozj2021-02-17  36

Many times the remote system will send it to the length of the data in the form of a digital. However, when using socket to send and receive digital data, take into account a problem: To convert data according to the type of the network. In particular, I need to know how to convert the data format (network format) to be sent into the format of the local machine (host format) into industry standard format.

Using ipaddress.networktohostorder, the data can be converted from the network rule to the host format. The following ReceiveHeader function illustrates its usage, the ReceiveHeader function implementation process is as follows:

1 Receive data from the remote machine with Socket.Receive.

2 Verify that the number of bytes received is 4.

3 Socket.Receive Returns a byte array, Bitconvert.Toint32 converts it into a digital value.

4 Finally, ipaddress.networktohostorder converts long values ​​to host format.

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;

}

Let's take a look at how to use multiple threaded methods to establish a connection for each string, and receive string data from the remote machine. In this case, the byte type data is to be converted into a String type object. You can convert with the ASCIIEncoding or UnicodeEncoding class as needed. The ReceiveDetail function is implemented as follows (this function must be called after ReceiveHeader, because the value of DataSize is obtained from the ReceiveHeader.)

1 Call Socket.Receive in the While loop until there is no return value. Data is read into a byte array.

2 Create an ASCIIENCoding object.

3 Call asciiencoding.getstring converts the byte array into a String object and then connects it and the previously read data.

Public String ReceiveDetail (socket socket, byte [] buffer,

Int Datasize)

{

String response = ""

INT BYTESRECEIVED = 0;

INT TOTALBYTESRECEIVED = 0;

While (0 <(bytesReceived =

Socket.Receive (Buffer, DataSize - TotalbytesReceive),

Socketflags.none)))))))))

{

TotalbytesReceived = bytesReceived;

ASCIENCODING Encoding = new asciiencoding ();

Response = encoding.getstring (buffer, 0, bytesreceive);

}

Return Response;

}

转载请注明原文地址:https://www.9cbs.com/read-29048.html

New Post(0)