Hello Everyone,

I am trying to write a small server for a project of mine, i have the loop i want to use to check for connections but im having trouble getting it to run in the background. I have a button on my windows form that i want to enable to disable the loop but im not sure how to go about it?

My class code is below, it works but it causes the application to stop responding but my cleint can still send and recieve the messages.

any ideas?

Code:
Public Class clsServe
    Shared Sub tcpListen()
        ' Must listen on correct port- must be same as port client wants to connect on.
        Const portNumber As Integer = 8000
        Dim localAddr As IPAddress = IPAddress.Any

        Dim tcpListener As New TcpListener(localAddr, portNumber)
        tcpListener.Start()
        Try
            'Accept the pending client connection and return a TcpClient initialized for communication. 
            Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
            strConsoleMessage = "Communication Sarted"
            ConsoleWrite()
            ' Get the stream
            Dim networkStream As NetworkStream = tcpClient.GetStream()
            ' Read the stream into a byte array
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            ' Return the data received from the client to the console.
            Dim clientdata As String = Encoding.ASCII.GetString(bytes)
            strConsoleMessage = clientdata
            Dim responseString As String = "Connected to server."

            If clientdata.Contains("skunk02") Then
                Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("OK")
                networkStream.Write(sendBytes, 0, sendBytes.Length)
            Else
                Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("FAIL")
                networkStream.Write(sendBytes, 0, sendBytes.Length)
            End If

            strConsoleMessage = responseString
            ConsoleWrite()

            'Dim sendBytes2 As [Byte]() = Encoding.ASCII.GetBytes(responseString & "Hello")

            'networkStream.Write(sendBytes2, 0, sendBytes2.Length)
            'Any communication with the remote client using the TcpClient can go here.
            'Close TcpListener and TcpClient.
            tcpClient.Close()
            tcpListener.Stop()
            strConsoleMessage = "Transaction Complete"
            ConsoleWrite()
        Catch ex As Exception
            tcpListen()
        End Try
        tcpListen()

    End Sub
End Class