首页 > 解决方案 > 如何正确监听传入的 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#tcplistener

解决方案


推荐阅读