【问题标题】:EndReceive in Async Socket without strings没有字符串的异步套接字中的 EndReceive
【发布时间】:2020-03-02 00:29:09
【问题描述】:

我正在关注这个关于在 C# 中创建异步 tcp 侦听器的示例。 MSDN Example

我看到所有数据都被编码为字符串以检查消息的完整性。更准确地说,发送的每条消息都已经是一个字符串,我们将 'EOF' 字符附加到该字符串以终止字符串。

我所说的服务器端部分在这个 sn-p 中:

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

        // Check for end-of-file tag. If it is not there, read   
        // more data.  
        content = state.sb.ToString();  
        if (content.IndexOf("<EOF>") > -1) {  
            // All the data has been read from the   
            // client. Display it on the console.  
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",  
                content.Length, content );  
            // Echo the data back to the client.  
            Send(handler, content);  
        } else {  
            // Not all data received. Get more.  
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,  
            new AsyncCallback(ReadCallback), state);  
        }  
    }  
}  

有没有办法,就像我通常对 TcpListener/TcpClient 类所做的那样,检查接收到的字节是否在套接字上可用?

我的意思是这样的:

    private void HandleClientConnection(TcpClient client)
    {
        NetworkStream clientStream = client.GetStream();

        MemoryStream memoryStream = new MemoryStream();

        while (true)
        {
            int read = clientStream.ReadByte();

            if (read != -1)
            {
                memoryStream.WriteByte((byte)read);
            }
            else
            {
                break;
            }
        }
    }

我知道我可能误解了这个例子,或者至少误解了开始/结束部分和“遗留”异步模式。但这是我的目标,你知道什么方法可以让它在不涉及字符串的情况下工作吗?

【问题讨论】:

    标签: c# sockets asynchronous tcplistener asyncsocket


    【解决方案1】:

    你说:“有没有办法检查接收到的字节是否在套接字上可用?”

    一般来说,'EndReceive' 会阻塞线程,直到数据可用。因此,您无需执行任何操作,因为“EndReceive”正在为您完成所有工作。

    'bytesRead' 是一个 int,它显示你收到了多少数据。

    来自 docs.microsoft 的引述

    EndReceive 方法将阻塞直到数据可用。1

    但如果您使用的是 SYNC 套接字(您不是),那就是另一个话题了。

    【讨论】:

    • 感谢您的回答。因此,我认为本示例中发生的所有字符串构建器都与示例域(完整字符串发送/接收)有关。你同意吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多