繁体   English   中英

TcpListener从C#中的套接字读取数据时出现问题

[英]Problems with TcpListener reading data from socket in c#

我在使用C#中的BeginReceive / BeginSend读取从TcpClient发送到TcpListener的大消息时遇到麻烦。

我试图在邮件中附加一个四字节长的标头,但有时我不会将它作为第一个引起问题的数据包接收。

例如,我发送了一个序列化对象,该对象包含[204、22、0、0]值作为BeginSend中字节数组的前四个字节。 我在BeginReceive上在服务器上收到的是[17,0,0,0]。 发送简单的字符串时,我已经检查了Wireshark,并且消息正在通过中,但是我的代码有问题。 另一个示例是,当我发送“ A bcdefghijklmnopqrstuv wxyz 1 2 3 4 5 6 7 8 9 0”以测试我不断收到“ pqr ... 8 9 0”时。

我认为,如果数据包接收混乱或丢失,TCP将处理丢失的数据包的重新提交和/或在发送之前对它们重新排序。 这意味着我的前四个字节应始终在标头中包含我的消息大小。 但是,看看上面的示例,情况并非如此,否则,我的代码被弄乱了。

在下面的代码之后,我只是看它是否正在发送特定的命令或对象类型,然后根据收到的内容进行响应。

我拥有适当的核心功能,可以更好地理解我可以开始重构的问题,但这确实让我停滞不前。

数天来,我一直在试图将其调试到墙壁上。 我已经阅读了几篇有关类似问题的文章和问题,但是我还没有找到将建议的修复程序应用于此特定实例的方法。

在此先感谢您的协助。

以下代码中的YahtzeeClient只是带有playerinformation信息的TcpClient的包装。

    private void ReceiveMessageCallback(IAsyncResult AR)
    {
        byte[] response = new byte[0];
        byte[] header = new byte[4];
        YahtzeeClient c = (YahtzeeClient)AR.AsyncState;
        try
        {
            // If the client is connected
            if (c.ClientSocket.Client.Connected)
            {
                int received = c.ClientSocket.Client.EndReceive(AR);

                // If we didn't receive a message or a message has finished sending
                // reset the messageSize to zero to prepare for the next message.
                if (received == 0)
                {
                    messageSize = 0;

                    // Do we need to do anything else here to prepare for a new message?
                    // Clean up buffers?
                }
                else
                {
                    // Temporary buffer to trim any blanks from the message received.
                    byte[] tempBuff;

                    // Hacky way to track if this is the first message in a series of messages.
                    // If messageSize is currently set to 0 then get the new message size.
                    if (messageSize == 0)
                    {
                        tempBuff = new byte[received - 4];

                        // This will store the body of the message on the *first run only*.
                        byte[] body = new byte[received - 4];

                        // Only copy the first four bytes to get the length of the message.
                        Array.Copy(_buffer, header, 4);

                        // Copy the remainder of the message into the body.
                        Array.Copy(_buffer, 4, body, 0, received - 4);

                        messageSize = BitConverter.ToInt32(header, 0);

                        Array.Copy(body, tempBuff, body.Length);
                    }
                    else
                    {
                        // Since this isn't the first message containing the header packet
                        // we want to copy the entire contents of the byte array.
                        tempBuff = new byte[received];
                        Array.Copy(_buffer, tempBuff, received);
                    }

                    // MessageReceived will store the entire contents of all messages in this tranmission.
                    // If it is an new message then initialize the array.
                    if (messageReceived == null || messageReceived.Length == 0)
                    {
                        Array.Resize(ref messageReceived, 0);
                    }

                    // Store the message in the array.
                    messageReceived = AppendToArray(tempBuff, messageReceived);

                    if (messageReceived.Length < messageSize)
                    {
                        // Begin receiving again to get the rest of the packets for this stream.
                        c.ClientSocket.Client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveMessageCallback, c);
                        // Break out of the function.  We do not want to proceed until we have a complete transmission.
                        return;
                    }

                    // Send it to the console
                    string message = Encoding.UTF8.GetString(messageReceived);

**标记为已解决。 解决方案是将消息包装在消息头和消息终止符的末尾,然后修改代码以查找这些指示符。

使用套接字的原因是由于对项目的限制,使得无法使用Web服务。

您遇到问题是因为您不知道第一个消息的大小,有时会越来越多,有时会越来越少,有时您会得到缓存中剩余的一些信息...

一个简单的解决方案是始终在实际消息之前发送消息大小,例如:

[MYHEADER] [32位整数] [消息内容]

让我们假设MYHEADER是ASCII,只是一个虚拟标识符,在这种情况下,我将:

1:尝试接收12个字节以捕获整个标头(MYHEADER + 32Bit Integer),直到您执行任何操作。 此后,如果标头标识符不是MYHEADER,则我将假定该消息已损坏,并且在连接中将发生诸如复位的情况。

2:确认报头正常后,我将检查消息大小的32位整数并分配必要的缓冲区。 (您可能想在此处限制内存使用,最大为6Mb,如果您的消息超出此范围,请在32位整数之后添加一个索引以指定消息部分...)

3:尝试接收直到标题中指定的邮件大小。

您似乎对TCP是无边界的字节流这一事实不太了解。 例如,如果读取的标题少于4个字节,则标题读取将失败。

接收长度前缀消息的一种非常简单的方法是使用BinaryReader

var length = br.ReadInt32();
var data = br.ReadBytes(length);

就这样。 使自己熟悉所有标准的BCL IO类。

通常,最好不要使用套接字。 使用更高级别的协议。 WCF很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM