C# 监听端口的服务

标签 c# service tcp windows-services server

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

由于某种原因,当我尝试启动该服务时,该服务超时了。我的日志告诉我 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
        {
        }
    }

最佳答案

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

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

干杯

关于C# 监听端口的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044052/

相关文章:

silverlight - 如何从 SilverLight 打开 TCP 套接字?

c# - 我应该重载 == 运算符吗?

c# - ObservableCollection<> 不会绑定(bind)更改

c# - 文件未找到异常 - System.Runtime,版本 = 4.1.1.0

c# - 无法从命令行或调试器启动服务

xcode - 检查服务菜单中的服务是否可用

android - IntentService 工作队列状态

c# - 如何在客户端检测关闭的 StreamSocket

c# - 检查 Excel dll 并动态加载

tcp - 在Rust中设置std::net::TcpStream的发送缓冲区大小