读取拆分TCP数据包

时间:2011-03-13 13:29:35

标签: c# .net tcp packet custom-protocol

我已经编写了大部分代码来处理我服务器的传入数据包。数据包的格式始终为int / int / int / string / string,第一个int是数据包的大小。我需要找出一些方法来检查并查看整个数据包是否到达,或者我是否需要等待更多的部分进入,但是按照我编写代码的方式,我想不出一个好方法。任何帮助都会很棒,因为我的大脑可能会过度思考这个问题。

private void ReadClientPacket(object client)
{
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();

    while (true)
    {
        try
        {
            int packetsize;

            // Create a new Packet Object and fill out the data from the incoming TCP Packets
            RCONPacket packet = new RCONPacket();

            using (BinaryReader reader = new BinaryReader(clientStream))
            {
                // First Int32 is Packet Size
                packetsize = reader.ReadInt32();

                packet.RequestId = reader.ReadInt32();
                packet.ServerDataSent = (RCONPacket.SERVERDATA_sent)reader.ReadInt32();

                Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, packet.RequestId, packet.ServerDataSent);

                // Read first and second String in the Packet (UTF8 Null Terminated)
                packet.String1 = ReadBytesString(reader);
                packet.String2 = ReadBytesString(reader);

                Console.WriteLine("String1: {0} String2: {1}", packet.String1, packet.String2);
            }

            switch (packet.ServerDataSent)
            {
                case RCONPacket.SERVERDATA_sent.SERVERDATA_AUTH:
                {
                    ReplyAuthRequest(packet.RequestId, clientStream);
                    break;
                }
                case RCONPacket.SERVERDATA_sent.SERVERDATA_EXECCOMMAND:
                {
                    ReplyExecCommand();
                    break;
                }
                default:
                {
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            break;
        }
    }

    tcpClient.Close();
}

1 个答案:

答案 0 :(得分:1)

你应该工作,因为底层流将等待更多数据。也就是说,如果您要调用clientStream.ReadByte并且没有任何可用字节,则该方法将阻塞,直到数据进入或直到流关闭为止 - 在这种情况下,可能已被服务器断开连接。

BinaryReader将会有足够的数据来满足读取请求,因此代码应该按预期工作。

相关问题