c#服务监听一个端口

c# service to listen to a port

我相信我要创建的是一个侦听特定端口的服务,当数据发送到该端口时,它会将数据发送到另一个脚本进行处理。

但由于某种原因,当我尝试启动服务时服务超时。我的日志告诉我 TcpClient client = server.AcceptTcpClient(); 是它停止的地方(实际上,它卡在服务中的 'starting')。

由于我没有使用 C#、制作服务或以这种方式使用服务器的经验,因此代码几乎就是我在网上找到的。

OnStart 方法如下所示。

    protected override void OnStart(string[] args)
    {
        try
        {
            TcpListener server = null;
            // Set the TcpListener on port 13000.
            Int32 port = 1234;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

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

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = server.AcceptTcpClient();

                data = null;

                // Get a stream object for reading and writing
                NetworkStream 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.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

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

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                }

                // Shutdown and end connection
                client.Close();
            }
        }
        catch (SocketException e)
        {
        }
        finally
        {
        }
    }

根据 MSDN,TcpServer.AcceptTcpClient 块,因此您可能永远不会 return 从服务的 OnStart 方法中调用,这会导致服务实际上永远不会 "start" .

您可以考虑尽快使用 OnStart 中的另一个线程和 return。

干杯

就创建 Windows 服务本身而言,您应该能够使用 this link, even though it's dated. This companion link shows how to have the service install and uninstall itself. Finally, use this link 来了解如何让您的服务 运行 持续运行以及如何正确响应启动和停止命令。

要让您的服务与套接字交互,您需要修改最后一个 link 中的 WorkerThreadFunc()。这是您应该开始侦听和处理入站套接字连接的地方。