Click here to Skip to main content
15,896,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've got the basis of the program working (I'm doing a lot of experimentation here as this is the first real program I'm writing) And I had everything working perfectly with simple button click events. But, my issue is I need to have a tcplisten running in the background.

I have found out through a little bit of research that I need to use threads. All good.
The listen thread works as required. Holds the port open, receives the data, passes that onto my texbox creator. But I can't get the textbox to actually go onto the flowlayoutpanel.

VB
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        tcpthread = New System.Threading.Thread(AddressOf tcplisten.MyTcpListener.Main)
        tcpthread.Start()
        txtthread = New System.Threading.Thread(AddressOf txtboxcreate)
        txtthread.Start()
        textboxestime = New Dictionary(Of TextBox, Integer)
        textboxestime.Add(Nothing, 0)
    End Sub



Public Class tcplisten
    Public Shared datastring As String
    Public Shared received As Boolean
    Class MyTcpListener
        Public Shared Sub Main()
            Dim lf As Decimal = 23
            Dim server As TcpListener
            Dim datastring As String = Nothing
            server = Nothing

                Try
                    ' Set the TcpListener on port 13000. 
                    'Dim port As Int32 = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Iain-KVS", "p1", Nothing)
                    '  Dim ipstring As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Iain-KVS", "IP", Nothing)
                    Dim port As Int32 = 13000
                    Dim localaddr As IPAddress = IPAddress.Parse("127.0.0.1")
                    server = New TcpListener(localaddr, port)

                    ' Start listening for client requests.
                server.Start()

                '    server.AcceptSocket()

                ' Buffer for reading data 
                Dim bytes(1024) As Byte
                Dim data As String = Nothing

                ' Enter the listening loop. 
                'While True
                '         MsgBox("Waiting for a connection... ")

                ' Perform a blocking call to accept requests. 
                ' You could also user server.AcceptSocket() here. 
                Dim client As TcpClient = server.AcceptTcpClient()

                ' 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)
                'MsgBox(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)
                '         MsgBox("Sent: {0}", data)

                '              i = stream.Read(bytes, 0, bytes.Length)
                tcplisten.datastring = (data)
                client.Close()
                received = True
                Form1.txtboxcreate()

                ' End While

                ' Shutdown and end connection

            Catch e As SocketException
                Console.WriteLine("SocketException: {0}", e)
            Finally
                '   server.Stop()
            End Try
        End Sub 'Main
    End Class 'MyTcpListener
End Class


VB
Public Sub txtboxcreate()
        Dim check As Boolean
        check = tcplisten.received
        If check = True Then
            Dim name As String
            Dim text As String
            Dim counttotal As Integer
            Dim count As Integer
            Dim tb As New TextBox()
            text = tcplisten.datastring
            ' set the textbox dimensions being created
            name = ("TxtBox" & CStr(counttotal))
            With tb
                .Name = name
                .Text = text
                .Multiline = True
                .Height = 150
                .Width = 250
                .ReadOnly = True
                .ScrollBars = False
                .MaxLength = 100
                .Tag = 20
                .BackColor = Color.Black
                .ForeColor = Color.White
                '           move unused properties under here'
                '           tb.ScrollBars = ScrollBars.Both
                '           tb.MaxLength = 100
                '           tb.Height = 100
                '           tb.AutoSize = True
                ' add events to the textbox created
                Me.FlowLayoutPanel1.Controls.Add(tb)
                Form1.textboxestime.Add(tb, 0)
                AddHandler tb.MouseClick, AddressOf Me.TextBox1_MouseClick
            End With
            count = (count + counttotal)
        End If
    End Sub


I can see it being passed from the tcplistener through to txtboxcreate without an issue, but it just does not seem to be adding the textbox to the flowlayoutpanel.
Posted

1 solution

First of all, if you use the TcpListener, or socket programming on the server side in general, you hardly can avoid using at least two threads for communication: one for accepting new clients connecting your server side, and other thread for communication between them. Please see my past answers for further detail and some ideas:
an amateur question in socket programming[^],
Multple clients from same port Number[^].

Now, about the thread method you show. You cannot do such things.

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900