我正在关注此示例,该示例有关在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部分和“旧版”异步模式。但这是我的目标,您知道不使用字符串就可以使其正常工作的方法吗?