【问题标题】:A listener TCP/IP socket in a windows serviceWindows 服务中的侦听器 TCP/IP 套接字
【发布时间】:2018-04-07 04:59:52
【问题描述】:

我想创建一个 Windows 服务来运行侦听器 TCP/IP 套接字。侦听器 TCP/IP 套接字具有“While True”循环并在 Windows 应用程序中工作。我有一个带有计时器的简单 Windows 服务,它可以工作,但是当我在 Windows 服务中包含 TCP/IP 套接字时它不起作用。我收到一条错误消息:“本地计算机上的 XXX 服务已启动然后停止。如果某些服务没有被其他服务或程序使用,它们会自动停止。”有人对此有任何线索吗?

这是启动 TCP/IP 监听器的基本代码:

    Dim bytes() As Byte = New [Byte](1024) {}

    localEndPoint = New System.Net.IPEndPoint(IPA, C_PORT)
    listener = New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, _
        System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
    listener.Bind(localEndPoint)
    listener.Listen(10)
    While True
        Dim handler As System.Net.Sockets.Socket = listener.Accept()
        data = Nothing
        While True
            bytes = New Byte(1024) {}
            Dim bytesRec As Integer = handler.Receive(bytes)
            data += System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec)
            If data.IndexOf(Chr(28) & Chr(13)) > -1 Then
                Exit While
            End If
        End While
        s = data
        Dim m As M2_GIS.Tools.HL7.C_Message
        m = New M2_GIS.Tools.C_Message
        m.MessageString = s
        m.P_Read()
        m.P_GetMessageData()
        Dim Response As String
        Response = m.F_ReceivedAcknowledgement
        A2_p1.Value = s
        A2_p12.Value = Response
        m.DaedalusPK = CInt(A2_Cmd.ExecuteScalar)
        m.P_UpdateDatabase()
        Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(Response)
        handler.Send(msg)
        handler.Shutdown(System.Net.Sockets.SocketShutdown.Both)
        handler.Close()
    End While

listener 和 localEndPoint 是类的属性。 M2_GIS.Tools.HL7.C_Message 类只是我自己处理传入消息的类。A2_ 变量用于运行 SQL Server 存储过程以将消息保存在数据库中。

【问题讨论】:

标签: vb.net service tcp-ip


【解决方案1】:

我怀疑您的服务线程已结束,因为监控可能设置不正确。

Dim listener As New TcpListener(8000)

listener.Start()

While(True)

// Wait for data from client, do some stuff

End While

listener.Stop()

这应该让您的服务保持运行。

【讨论】:

  • 我拥有的代码(见下文)运行正常
  • 感谢您的回复。我的代码作为 Windows 应用程序运行得很好,但它在 Windows 服务中不起作用。所以代码本身并没有什么问题,除非有与windows服务不兼容的东西,我不知道。我正在使用的侦听器没有启动方法。 listener = New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp) 我使用绑定和监听方法。再次感谢您。
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 2017-07-20
  • 2015-01-20
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
相关资源
最近更新 更多