C#TCPClient侦听传入的消息

时间:2018-08-17 09:37:31

标签: c# tcpclient

我有一个TCPClient,它应该侦听来自c&c的传入消息。消息结构应为:缓冲区(字节数组),类型(整数/字符串),ID(整数)和参数(字符串数组)。

我找到了以下用于侦听传入消息的代码:

Byte[] bytes = new Byte[1024];
while (true)
{
    // Get a stream object for reading              
    using (NetworkStream streamFromServer = client.GetStream())
    {
        int length;
        // Read incomming stream into byte arrary.                  
        while ((length = streamFromServer.Read(bytes, 0, bytes.Length)) != 0)
        {
            var incomingData = new byte[length];
            Array.Copy(bytes, 0, incomingData, 0, length);
            // Convert byte array to string message.                        
            string serverMessage = Encoding.ASCII.GetString(incomingData);
        }
    }
}

如何使用缓冲区读取消息?另外,如何将incomingData转换为我的消息结构?

0 个答案:

没有答案