我在使用套接字编程TCP客户端/服务器时遇到了麻烦。 我做了一个使用我在这里找到的MSDN示例的小程序:http://msdn.microsoft.com/en-us/library/bew39x2a%28v=vs.110%29.aspx 但是有一些修改,比如发送功能上的队列:
public void Send(String data)
{
// Wait for server connection
if (connectDone.WaitOne())
{
// If already sending data, add to the queue
// it will be sent by SendCallback method
if (_sending)
{
_queue.Enqueue(data);
}
else
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
_sending = true;
SocketHolder.BeginSend(byteData, 0, byteData.Length, 0, SendCallback, SocketHolder);
}
}
}
服务器通过readcallback函数读取数据:
public 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));
// Check for end of message tag & raise event
content = state.sb.ToString();
if (content.IndexOf("</MetrixData>") > -1)
{
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
OnMessageReceived(EventArgs.Empty, content);
state.sb = new StringBuilder(); // Clear the message from state object string builder
}
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, ReadCallback, state);
}
}
嗯,现在这是我的问题:我的应用程序的重点是以高频率向服务器发送变量(每个变量每秒最多60次)。 但是,当我尝试快速更新我的数据时,我的状态对象的字符串构建器似乎没有时间正确清理,因为我在OnMessageReceived函数中同时重复多个数据(这是一个问题,因为我序列化我发送的每个数据,所以我最终在服务器收到的消息中有多个根元素。
如果您想仔细查看整个项目here(不确定我的解释是否清楚......)
提前感谢您的帮助&amp;你的时间:)
编辑:抱歉,我会尽力解释一下我的问题:p
这是一个发送的消息示例&amp;单独更新数据时正确收到。
<MetrixData>
<DataId>IntTest</DataId>
<Type>System.Int32</Type>
<Value TimeStamp="22/07/14 22:22:19">10</Value>
</MetrixData>
如果我在很短的时间内对我的数据进行多次更新,这就是我的服务器收到的内容。
<MetrixData>
<DataId>IntTest</DataId>
<Type>System.Int32</Type>
<Value TimeStamp="22/07/14 22:25:06">12</Value>
</MetrixData><MetrixData>
<DataId>IntTest</DataId>
<Type>System.Int32</Type>
<Value TimeStamp="22/07/14 22:25:06">13</Value>
</MetrixData><MetrixData>
<DataId>IntTest</DataId>
<Type>System.Int32</Type>
<Value TimeStamp="22/07/14 22:25:06">14</Value>
</MetrixData>
(可以同时收到2,3或最多10条消息)
我无法弄清楚为什么我的ReadCallback没有检测到当前消息的结束并且没有重置缓冲区应该由ReadCallBack示例完成
// Check for end of message tag & raise event
content = state.sb.ToString();
if (content.IndexOf("</MetrixData>") > -1)
{
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
OnMessageReceived(EventArgs.Empty, content);
state.sb = new StringBuilder(); // Clear the message from state object string builder
}
答案 0 :(得分:1)
TCP为您提供字节流。 TCP中没有消息。您可能在一次读取中收到两条逻辑消息。这会导致您的处理在您希望它运行两次时执行一次。
如果你想要消息语义,你必须自己实现它们。通常,原始TCP连接开始时是错误的。为什么不使用HTTP或Web服务等更高级的原语?至少,使用protopuf作为序列化格式。如果你做了这些中的任何一个问题就不会发生。当你自己实施有线协议时,会有更多的地雷在你前面。
此外,一旦超出ASCII范围(换句话说,当此应用程序投入生产时),您的字符串编码将失败。同样,这个问题只存在,因为你正在做所有这些低级别的工作。通过网络电缆发送消息和字符串已自动为您服务。利用这项工作。
答案 1 :(得分:0)
这是我的猜测。我认为没有数据包导向(UDP),你只需要一个连续的TCP流。您需要实现其中之一:
消息信封就像这样简单:
这是一个快速的提升:
// NetworkStream ns; <-- already set up
using(MemoryStream memory = new MemoryStream())
using(BinaryWriter writer = new BinaryWriter(memory))
{
// all output to writer goes here
// now close the envelop and send it:
byte[] dataBuffer, sizeBuffer;
dataBuffer = memory.ToArray();
sizeBuffer = BitConverter.GetBytes(dataBuffer.Length);
ns.SendBytes(sizeBuffer, 0, 4); // send message length (32 bit int)
ns.SendBytes(dataBuffer, 0, dataBuffer.Length); // send message data
}
在该行的另一端,您将打开信封并使用相反的步骤提取消息:
// NetworkStream ns; <-- already set up
byte[] sizeBuffer, dataBuffer;
int size;
sizeBuffer = new byte[4];
ns.ReadBytes(sizeBuffer, 0, 4); // read message length
size = BitConverter.ToInt(sizeBuffer);
dataBuffer = new byte[size];
ns.ReadBytes(dataBuffer, 0, size); // read message data
using(MemoryStream memory = new MemoryStream(dataBuffer))
using(BinaryReader reader = new BinaryReader(memory))
{
// all input from reader goes here
}