Hi,
I worked on this listener alone ( I did not try to connect any clients to it until now).
I have this problem.
When starting the listener it started OK without any problem. so I added a stop listener button to this application and I tried to do listener.stop() but it throws an exception System.NullReferenceException
until now I did not try to connect any client after the listener started.
How I gracefully shut down this listener without the exception ?
Code:
Imports System.IO, System.Net, System.Net.Sockets
Public Class frmServer
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ClientList As New List(Of ChatClient)
Dim sReader As StreamReader
Dim cClient As ChatClient
Sub xLoad() Handles Me.Load
Listener = New TcpListener(IPAddress.Any, 3818)
Listener.Start()
xUpdate("Server Started", False)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
AddHandler (cClient.MessageRecieved), AddressOf MessageRecieved
AddHandler (cClient.ClientExited), AddressOf ClientExited
ClientList.Add(cClient)
xUpdate("New Client Joined", True)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub MessageRecieved(ByVal Str As String)
xUpdate(Str, True)
End Sub
Sub ClientExited(ByVal Client As ChatClient)
ClientList.Remove(Client)
xUpdate("Client Exited", True)
End Sub
Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
Else
txtMainTextBox.AppendText(Str & vbNewLine)
If Relay Then Send(Str)
End If
End Sub
Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSendTextBox.KeyDown
End Sub
Sub Send(ByVal Str As String)
For i As Integer = 0 To ClientList.Count - 1
Try
ClientList(i).Send(Str)
Catch
ClientList.RemoveAt(i)
End Try
Next
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Me.txtSendTextBox.Text = "" Then
Exit Sub
End If
xUpdate("Server Says: " & Me.txtSendTextBox.Text, True)
txtSendTextBox.Clear()
End Sub
Private Sub btnStopListener_Click(sender As Object, e As EventArgs) Handles btnStopListener.Click
Listener.Stop()
'this part stopped the listener but it throws an exception
End Sub
End Class