How do you stop TcpListener?

korae

Member
Joined
Jan 24, 2010
Messages
22
Programming Experience
Beginner
How do you stop TcpListener? I mean if the admin wants to change username or port in the server?

Private listener As TcpListener

Private listenThread As Thread

Private clients As New List(Of ConnectedClient)

This is where I start to listen from clients:

listener = New TcpListener(IPAddress.Any, txtPort.Text)
listener.Start() 'Start listening.
listenThread = New Thread(AddressOf DoListen)
listenThread.IsBackground = True
listenThread.Start()

And here's the DoListen

Private Sub DoListen()
Dim incomingClient As System.Net.Sockets.TcpClient
Do
incomingClient = listener.AcceptTcpClient
Dim connClient As New ConnectedClient(incomingClient, Me)
AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
clients.Add(connClient) 'Adds the connected client to the list of connected clients.
Me.MessageReceived
Loop
End Sub

How do you stop listener? I tried doing this but I always get an error:

listener.Stop()
listenThread.Abort()
 
One way to do it:
VB.NET:
Private cancelServer As Boolean

Private Sub DoListen()
    Do Until cancelServer
        If listener.Pending Then
            Dim incomingClient As Net.Sockets.TcpClient = listener.AcceptTcpClient

        End If
        Thread.Sleep(100)
    Loop
End Sub
VB.NET:
cancelServer = True
listener.Stop
 
Back
Top