Cary Bondoc
Cary Bondoc

Reputation: 2988

Basic tcp/ip that runs on a separate thread (to prevent freeze)

I want to create a basic tcp/ip server that listens on all IP as long as it is on port 7700, based on my research what I need is to run it on another thread to prevent my system from being freeze. I combined 2 examples from MSDN's basic TCP/IP listener and CodeGuru's basic thread tutorial.

For the UI, I only have a button and a richtextbox. I am planning to use this button to start the listening on port "7700" then whenever I received a message from a client I want it to be appended on RichTextBox1

My problem is that, my system still freezes whenever I started listening.

I have this code:

Imports System.Net.Sockets
Imports System.Net
Imports System.Threading 'Imports Threading Namespace

Public Class Form1

    ' Set the TcpListener on port 13000. 
    Dim port As Int32 = 7700
    Dim localAddr As IPAddress = IPAddress.Any
    ' Buffer for reading data 
    Dim bytes(1024) As Byte
    Dim data As String = Nothing
    Dim server As TcpListener

    'What Thread 1 Must Do
    Private Sub ThreadProcedure()
        While True
            Console.Write("Waiting for a connection... ")
            ' Perform a blocking call to accept requests. 
            ' You could also user server.AcceptSocket() here. 
            Dim client As TcpClient = server.AcceptTcpClient()
            Console.WriteLine("Connected!")
            data = Nothing
            ' Get a stream object for reading and writing 
            Dim stream As NetworkStream = client.GetStream()
            Dim i As Int32
            ' Loop to receive all the data sent by the client.
            i = stream.Read(bytes, 0, bytes.Length)
            While (i <> 0)
                ' Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                Console.WriteLine("Received: {0}", data)
                ' Process the data sent by the client.
                data = data.ToUpper()
                Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
                ' Send back a response.
                stream.Write(msg, 0, msg.Length)
                Console.WriteLine("Sent: {0}", data)
                i = stream.Read(bytes, 0, bytes.Length)
            End While
            ' Shutdown and end connection
            'client.Close()
        End While
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        server = Nothing
        Try
            server = New TcpListener(localAddr, port)
            ' Start listening for client requests.
            server.Start()
            ' Enter the listening loop. 
            ThreadProcedure()
        Catch haha As SocketException
            Console.WriteLine("SocketException: {0}", haha)
        Finally
            'server.Stop()
        End Try
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Create Thread, and Specify Delegate
        Dim tThread1 As New Thread(AddressOf ThreadProcedure)
    End Sub
End Class

Upvotes: 0

Views: 1512

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27322

You have created a Thread in Form_Load but not started it, then in the button click you call the method directly.

Remove the code from the Form Load and put this in the Button Click:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        server = Nothing
        Try
            server = New TcpListener(localAddr, port)
            ' Start listening for client requests.
            server.Start()
            ' Enter the listening loop. 
            Dim tThread1 As New Thread(AddressOf ThreadProcedure)
            tThread1.Start()
        Catch haha As SocketException
            Console.WriteLine("SocketException: {0}", haha)
        Finally
            'server.Stop()
        End Try
    End Sub

Upvotes: 1

Related Questions