How to politely stop the TcpListener?
I have a TCP server running fine, but now I need to stop it and all threads in a safe way. As far as I know the Abort method doesn't work
I am debugging and when the server is started and has no connections, it seems like the code stops at the line
Server = New TcpListener(IPAddress.Any, Port)
So when I call StopServer I get WSACancelBlokingCall error I can't figure out how to stop the server properly.
Here the code, with the exception of StartTcpClient, was received by data.
#Region "TCP Receive variables"
Dim TcpOpen As Boolean = False
Private Server As TcpListener = Nothing
Private ServerThread As Thread = Nothing
Friend AckString As String = ""
#End Region
#Region "TCP"
Public Sub StopServer()
Server.Stop()
ServerThread.Abort()
TcpOpen = False
End Sub
Public Sub InitServer(ByVal Port As Integer)
Server = New TcpListener(IPAddress.Any, Port)
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
TcpOpen = True
End Sub
Private Sub ConnectionListener()
Server.Start()
While True
Dim client As TcpClient = Server.AcceptTcpClient()
Dim T As New Thread(AddressOf StartTcpClient)
T.IsBackground = True
T.Start(client)
End While
End Sub
#End Region
Edit: I am making some changes to the code and now it seems to work as I need.
Public Sub StopServer()
TcpOpen = False
Server.Stop()
ServerThread = Nothing
End Sub
Private Sub ConnectionListener()
Server.Start()
While True
If TcpOpen Then
If Server.Pending Then
Dim client As TcpClient = Server.AcceptTcpClient()
Dim T As New Thread(AddressOf StartTcpClient)
T.IsBackground = True
T.Start(client)
Else
System.Threading.Thread.Sleep(10)
End If
Else
Exit While
End If
End While
End Sub
source to share
-
The connection must be closed from the client (not the server).
-
The client must send an application message to the server to stop processing.
-
The server should stop processing
-
The server should execute BeginDisconnect
-
the server should send a response to the client indicating that the connection can be closed
-
The client should close the connection.
-
The server, when connecting to itself, should close / Dispose Listener.
source to share