首页 > 解决方案 > 为什么 TcpListener 不监听?

问题描述

我们有一个 C++ v100 应用程序,它正在处理我们系统中的每个事件,侦听端口 1705,运行主机名。(它非常适合 C++ 应用程序,我们不想更改 C++ 代码中的任何内容)我们试图将其中一些事件截获到 C# 4.5.2 解决方案中,只是为了在我们的新 Web 系统中显示特定事件.

我编写了以下代码,试图监听 1705 端口的流量……但我从未收到任何数据。(我可以创建发送到 1705 的事件)

以下代码运行,并使其变为“等待连接”,但从未变为“已连接!”。如果您在以下代码中看到我无法接收数据的任何原因,请告诉我:

    private void PortListener()
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            var port = 1705;
            var localAddr = IPAddress.Parse(Dns.GetHostAddresses(Environment.MachineName)[0].ToString());

            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            var bytes = new byte[256];

            // Enter the listening loop.
            while (true)
            {
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                var client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                // Get a stream object for reading and writing
                var stream = client.GetStream();

                int i;

                // Loop to receive all the data sent by the client.
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    //TODO:  Process the data
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server?.Stop();
        }
    }

标签: c#tcpclienttcplistener

解决方案


I'm doing this all wrong. In order to listen to an already opened Port, I need to use a TcpClient to connect and listen. Only a single TcpListener is allowed per port. Several TcpClients can connect at once. Sigh.


推荐阅读