没有字符串的异步套接字中的EndReceive

我正在关注此示例,该示例有关在C#中创建异步tcp侦听器的信息。 MSDN Example

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

我正在谈论的服务器端部分在以下代码段中:

JMenuBar

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

我的意思是这样的:

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,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,StateObject.BufferSize,new AsyncCallback(ReadCallback),state);  
        }  
    }  
}  

我知道我可能误解了这个示例,或者至少误解了Begin / End部分和“旧版”异步模式。但这是我的目标,您知道不使用字符串就可以使其正常工作的方法吗?

hopelove1983 回答:没有字符串的异步套接字中的EndReceive

您说:“有没有一种方法可以检查套接字上是否有收到的字节?”

通常,“ EndReceive”将阻塞线程,直到可用数据为止。因此,您不需要做任何事情,因为“ EndReceive”正在为您完成所有工作。

'bytesRead'是一个整数,它向您显示已收到多少数据。

docs.microsoft的报价

  

EndReceive方法将一直阻塞,直到有可用数据为止。1

但是,如果您正在使用SYNC套接字(不是),则这是另一个主题。

本文链接:https://www.f2er.com/3158358.html

大家都在问