我有一个带有以下代码的C# TPC Socket

public static 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));

            // HERE WE NEED TO MAKE SURE THAT THE MESSAGE IS COMPLETE, IF NOT THEN READ MORE DATA

            if (bytesRead == ***something***)
            {
                //Do something HERE...
            }
            else
            {
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }
        }

    }

将发送到TCP套接字的数据的格式如下:
c# - C#TCP套接字如何验证传入的字符串并对其进行处理-LMLPHP
所以每个消息的大小都可能不同。前10个字节和后4个字节总是固定的,但是有效负载是动态的。
因此,我必须通过截取有效负载大小位置的4个字节来实现一种验证消息大小的方法,这种方法只需要执行2+4+4+有效负载大小+4的和,这样我就可以在if语句中执行其他操作。
有什么建议或线索可以告诉你最好的方法吗?

最佳答案

你可以这样做:

static void ReadCallback(IAsyncResult ar)
{
    //put received bytes into queue for further processing
    //initiate BeginReceive
}

在另一个线程上:
static void ProcessMessages()
{
    while(true)
    {
        //read messages from queue
        //check message frames
    }
}

您可以在simplsockets、方法ProcessReceivedMessage中检查如何实现它。

10-04 19:50