我有一个带有以下代码的C# TPC Socket
:
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// HERE WE NEED TO MAKE SURE THAT THE MESSAGE IS COMPLETE, IF NOT THEN READ MORE DATA
if (bytesRead == ***something***)
{
//Do something HERE...
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
将要发送到TCP套接字的数据的格式如下:
因此每个消息的大小可以不同。前10个字节和后4个字节始终是固定的,但有效载荷是动态的。
因此,我必须通过截取PAYLOAD SIZE位置的4个字节来实现一种验证消息大小的方法,这种方法只需要做2 + 4 + 4 +有效负载大小+ 4的总和即可。可以输入if语句,在那儿我还要做其他事情。
有什么建议或线索可以做到这一点吗?
答案 0 :(得分:0)
您可以这样做:
static void ReadCallback(IAsyncResult ar)
{
//put received bytes into queue for further processing
//initiate BeginReceive
}
在另一个线程上:
static void ProcessMessages()
{
while(true)
{
//read messages from queue
//check message frames
}
}
您可以在simplsockets的方法ProcessReceivedMessage
中检查其实现方式。