c# - 如何正确监听传入的 TCP 消息并解析它们?
问题描述
我想创建一个监听传入消息的 TCP 套接字服务器。每当此侦听器收到传入消息时,都应获取这些消息。稍后我想引发一个事件并将该消息转发给其他处理程序。所以这基本上是我到目前为止所拥有的:
public class TcpReceiver : IDisposable
{
private readonly TcpListener tcpListener;
public TcpReceiver(IPAddress listenAddress, ushort listenPort)
{
tcpListener = new TcpListener(listenAddress, listenPort);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(HandleIncomingMessage, null);
}
private void HandleIncomingMessage(IAsyncResult asyncResult)
{
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(asyncResult);
try
{
NetworkStream tcpClientStream = tcpClient.GetStream();
using StreamReader streamReader = new StreamReader(tcpClientStream);
string messageText = streamReader.ReadToEnd();
// do things with the message
}
catch (Exception exception)
{
// error handling
}
tcpListener.BeginAcceptTcpClient(HandleIncomingMessage, null);
}
public void Dispose()
{
tcpListener?.Stop();
}
}
当向侦听器发送消息时,代码跳转到该messageText
行,并且在该断点之后调试器“丢失”/“消失”。几秒钟后,tcp 发送方收到一个超时错误,然后断点跳回到那个地方。现在messageText
包含已发送的消息。
我想知道代码是否有问题(例如,我是否必须多次分块阅读?)。基本上我想要的只是监听传入的消息,阅读该消息并处理它(引发一个事件)。
解决方案
推荐阅读
- c - 在 C 中的 switch 中定义的变量
- c# - 根据模型值检查单选按钮
- android - 运行时权限不适用于版本 8.0.0 和版本 8.1.0 (React Native - Android)
- jquery - 使用单个按钮隐藏和显示内容时,JQuery 切换不起作用
- react-native - 如何使用 react-native-elements 将按钮的标题右对齐?
- python - 有没有办法在 Python 中标记类?
- postgresql - 如何检查(withtrigger)创建时的表是否已被 PL/pgSQL 函数中的另一个表引用?
- cmake - CMake 找不到 Perl
- amazon-web-services - 缺少 AWS Codebuild 运行时
- c# - 等待后反应程序不会终止