如何正确侦听传入的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包含已发送的消息。

我想知道代码是否有问题(例如,我是否必须多次读取块?)。基本上,我想要做的就是侦听传入的消息,阅读该消息并对其进行处理(引发事件)。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)