【发布时间】:2023-04-03 23:50:01
【问题描述】:
我有一个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 Socket 的数据会这样形成:
因此,每条消息的大小都可以不同。前 10 个字节和后 4 个字节始终是固定的,但负载是动态的。
所以我必须通过截取 PAYLOAD SIZE 位置的 4 个字节来实现一种验证消息大小的方法,这种方法只需计算 2 + 4 + 4 + 有效负载大小 + 4 的总和,所以我可以输入 if 语句,我将在那里做一些其他的事情。
关于最佳方式的任何建议或线索?
【问题讨论】:
-
您确定收到的是字符串吗?
-
我收到一个字节数组
-
如果不是字符串数据,那么您可能不应该将其存储为字符串。
-
是的,我会删除它,你是对的
-
@John 你如何附加到字节数组而不是附加字符串?
标签: c# tcp tcplistener