【问题标题】:c# service to listen to a portc#服务监听端口
【发布时间】:2016-01-07 17:51:13
【问题描述】:

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

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

由于我没有使用 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
        {
        }
    }

【问题讨论】:

  • 我假设您的意思是 Windows 服务。你的OnStart() 方法是什么样的?
  • 提示:制作 Windows 服务(并测试它们)的一种简单方法是使用TopShelf - on Nuget。它为您提供了一个简单的 exe,您可以在命令行运行或作为服务安装和运行。

标签: c# service tcp windows-services server


【解决方案1】:

根据MSDN,TcpServer.AcceptTcpClient 会阻塞,因此您可能永远不会从 Service 的 OnStart 方法返回,这会导致服务永远不会真正“启动”。

您可以考虑使用另一个线程并尽快从 OnStart 返回。

干杯

【讨论】:

    【解决方案2】:

    就创建 Windows 服务本身而言,您应该可以使用 this link,即使它已过时。这个companion link 展示了如何让服务自行安装和卸载。最后,使用this link 了解如何让您的服务持续运行以及如何正确响应启动和停止命令。

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

    【讨论】:

    • 非常感谢。它似乎奏效了。我现在要修复下一个错误,哈哈。
    猜你喜欢
    • 2021-07-10
    • 2017-03-13
    • 2011-09-14
    • 2017-09-25
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    相关资源
    最近更新 更多