C#异步套接字客户端/服务器

时间:2014-07-22 20:08:32

标签: c# sockets tcp

我在使用套接字编程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
        }

2 个答案:

答案 0 :(得分:1)

TCP为您提供字节流。 TCP中没有消息。您可能在一次读取中收到两条逻辑消息。这会导致您的处理在您希望它运行两次时执行一次。

如果你想要消息语义,你必须自己实现它们。通常,原始TCP连接开始时是错误的。为什么不使用HTTP或Web服务等更高级的原语?至少,使用protopuf作为序列化格式。如果你做了这些中的任何一个问题就不会发生。当你自己实施有线协议时,会有更多的地雷在你前面。

此外,一旦超出ASCII范围(换句话说,当此应用程序投入生产时),您的字符串编码将失败。同样,这个问题只存在,因为你正在做所有这些低级别的工作。通过网络电缆发送消息和字符串已自动为您服务。利用这项工作。

答案 1 :(得分:0)

这是我的猜测。我认为没有数据包导向(UDP),你只需要一个连续的TCP流。您需要实现其中之一:

  • 恢复为UDP(可能使用Lidgren)=&gt;非常昂贵且耗时;
  • 使用分隔符=>分隔流需要一个明确定义的字母表和分隔符集,例如:在BSON(二进制JSON)中你有base-64字母表,可以使用任何非base-64字符作为分隔符suche为&#39; |&#39 ;;
  • 实现一个消息信封,允许您分离单个消息=&gt;这是你正在做的事情的自然解决方案。

消息信封就像这样简单:

  • 使用MemoryStream缓冲输出数据;
  • 使用BinaryWriter写入该缓冲区;
  • 发送&#34;发送/发送/提交/提交&#34;关闭信封并将其发送到NetworkStream的方法。

这是一个快速的提升:

// 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
}