【发布时间】: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