我尝试为特定应用程序设置服务器。 到目前为止我已经做了一个这样的测试程序:
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
localEndPoint = new IPEndPoint(ipAddress, 11000);
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Socket clientSocket = await listener.AcceptAsync();
byte[] buffer = new byte[1024];
int bytesRead = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
//Extract data from the buffer
}
问题是我从客户端收到的消息的大小各不相同,但它的长度包含在前 4 个字节中。 那么,如何读取前 4 个字节,设置缓冲区的大小,然后异步读取完整的消息呢?
通过继续探索如何找到满足我的请求的解决方案,我得出了以下结论。
/*The message I receive from the client is a list of datasets
* which consists of an ident (1 float) and 10 floats of data (for simplicity in reality it's more)
* The first 4 bytes are a float of the number of datasets in the packet
*/
float nbOfDataSets;
int index = 0;
int bytesRead = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
if (bytesRead > 0)
{
//Getting the number of datasets
nbOfDataSets = BitConverter.ToSingle(buffer, 0);
//Calculation of the number of bytes in the received packet
int nbOfDataFor1_Set = 11; //Ident + data
totalOfBytes = (nbOfDataFor1_Set * (int)nbOfDataSets) * 4; // * 4 because 1 float consists of 4 bytes
totalOfBytes += 4; //+4 for the first float representting the number of datasets
//Initialize the buffer that will contain the full packet
bufferAll = new byte[totalOfBytes + 4]; //+4 for spare
Array.Copy(buffer, bufferAll, bytesRead);
index = bytesRead;
while (index < totalOfBytes)
{
bytesRead = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
Array.Copy(buffer, 0, bufferAll, index, bytesRead);
index += bytesRead;
}
//Extract data from bufferAll ...
}
我不知道这是否是正确的方法,但似乎可行