【发布时间】: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 存储过程以将消息保存在数据库中。
【问题讨论】:
-
请包含一个最小的“工作”示例以重现您的问题中的问题。
-
欢迎来到 Stack Overflow!请阅读How to create a Minimal, Complete, and Verifiable example。