【问题标题】:c# TCP socket how to validate incoming string and process itc# TCP socket如何验证传入的字符串并处理它
【发布时间】:2023-04-03 23:50:01
【问题描述】:

我有一个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 Socket 的数据会这样形成:

因此,每条消息的大小都可以不同。前 10 个字节和后 4 个字节始终是固定的,但负载是动态的。

所以我必须通过截取 PAYLOAD SIZE 位置的 4 个字节来实现一种验证消息大小的方法,这种方法只需计算 2 + 4 + 4 + 有效负载大小 + 4 的总和,所以我可以输入 if 语句,我将在那里做一些其他的事情。

关于最佳方式的任何建议或线索?

【问题讨论】:

  • 您确定收到的是字符串吗?
  • 我收到一个字节数组
  • 如果不是字符串数据,那么您可能不应该将其存储为字符串。
  • 是的,我会删除它,你是对的
  • @John 你如何附加到字节数组而不是附加字符串?

标签: c# tcp tcplistener


【解决方案1】:

你可以这样做:

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中查看它是如何实现的。

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2021-12-26
    • 2016-03-20
    • 2020-01-10
    相关资源
    最近更新 更多