Hello, I'm using a modified version of a multiple client TCP server (View here, and trying to have the server add an item to the listbox when a client connects. I have tested, and the client and server can communicate perfectly. I recieve the data from the client, I can even show it in a message box. I cannot however, even with typed data, add it to the listbox. From this certain area in the code, I cannot add anything to the listbox. But, from different areas in the code (such as a button press) I can update data in the controls. I have tried this with a listview too, and a textbox. I just cannot manipulate the form elements from inside the method. Here is the code I am trying to use, I will try to make it obvious where I am trying to update the controls from. If anyone could tell me why they aren't being updated, that would be great!

ConnectedClient class :

Imports System.IO
Imports System.Net.Sockets
Public Class ConnectedClient
    Private cli As TcpClient
    Private uuid As String
    Public Property Name As String
        Get
            Return uuid
        End Get
        Set(Value As String)
            uuid = Value
        End Set
    End Property
    Sub New(ByVal Client As TcpClient)
        Dim r As New Random
        Dim x As String = String.Empty
        For i = 0 To 7
            x &= Chr(r.Next(65, 89))
        Next
        Me.Name = client.Client.RemoteEndPoint.ToString().Remove(client.Client.RemoteEndPoint.ToString.LastIndexOf(":")) & " - " & x
        cli = client
        cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
    End Sub
    Public Event GotMessage(ByVal Message As String, ByVal Client As ConnectedClient)
    Public Event Disconnected(ByVal Client As ConnectedClient)

    Sub Read(ByVal Result As IAsyncResult)
        Try
            Dim sr As New StreamReader(cli.GetStream())
            Dim msg As String = sr.ReadLine()
            RaiseEvent GotMessage(msg, Me)
            cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
        Catch ex As Exception
            Try
                Dim sr As New StreamReader(cli.GetStream())
                Dim msg As String = sr.ReadLine()
                RaiseEvent GotMessage(msg, Me)
                cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
            Catch
                RaiseEvent Disconnected(Me)
            End Try
        End Try
    End Sub

    Sub SendData(ByVal Message As String)
        Dim sw As New StreamWriter(cli.GetStream())
        sw.WriteLine(Message)
        sw.Flush()
    End Sub
End Class

Server Class:

    Dim t As TcpListener
    Dim isRunning As Boolean
    Dim Port As Integer = 5440
    Dim split as String = "|"
    Sub Recieved(ByVal Message As String, ByVal Client As ConnectedClient)
        Dim msg() As String = Message.Split(split)
        Select Case msg(0)
            ' switch case on server return
            Case "Login"
                clients.Add(Client, Client.Name)
                TextBox1.AppendText("Connected - " & Client.Name & vbNewLine)
                '' //// Trying to update here //// ''
                '' //// ''
                '' //// ''
                '' //// ''
        End Select
    End Sub
    Sub Disconnected(ByVal Client As ConnectedClient)
    MsgBox(Client.Name & " lost connection.")
    End Sub
    Sub Listen()
    If isRunning = False Then
        Try
            StatusMessage = "Attempting to start listening on port " & Port
            t = New TcpListener(IPAddress.Any, Port)
            t.Start()
            StatusMessage = "Started listening on port " & Port
            isRunning = True
            Do
                Dim client As New ConnectedClient(t.AcceptTcpClient)
                AddHandler client.GotMessage, AddressOf Recieved
                AddHandler client.Disconnected, AddressOf Disconnected
            Loop
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End If
End Sub
Dim listener As New System.Threading.Thread(AddressOf Listen)
Private Sub StartListeningToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles StartListeningToolStripMenuItem.Click
    If isRunning = False Then
        listener.IsBackground = True
        listener.Start()
    End If
End Sub

And ofcourse, the client code:

Dim t As New TcpClient
    Dim split As String = "|"
    Dim IP As String = "localhost", Port As Integer = 5504


    Sub Connect()
        Try
            t.Connect(IP, Port)
            If t.Connected Then
                t.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
                SendData("Login" & split)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Connect()
        End Try
    End Sub
    Sub SendData(ByVal Message As String)
        Dim sw As New StreamWriter(t.GetStream())
        sw.WriteLine(Message)
        sw.Flush()
    End Sub
    Sub MessageRecieved(ByVal Message As String)
        Dim msg() As String = Message.Split(split)
        MsgBox(Message)
        Select Case msg(0)
            ' Server sent something back!

        End Select
    End Sub
    Sub Read(ByVal ar As IAsyncResult)
        Try
            Dim sr As New StreamReader(t.GetStream)
            Dim msg As String = sr.ReadLine()
            MessageRecieved(msg)
            t.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
        Catch ex As Exception
            MsgBox(ex.Message)
            Connect()
        End Try
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Connect()
    End Sub

Sorry for such a long post of code, but I just wanted to make sure that everything you would need to see the program was there.

First of all, your code doesn't compile. You're missing the following:

Dim clients As New Hashtable

In Server, try the following:

Sub Recieved(ByVal Message As String, ByVal Client As ConnectedClient)
    Dim msg() As String = Message.Split(split)
    Select Case msg(0)
        ' switch case on server return
        Case "Login"
            clients.Add(Client, Client.Name)
            ListBox1.Items.Add("Connected - " & Client.Name & vbNewLine)
            '' //// Trying to update here //// ''
            '' //// ''
            '' //// ''
            '' //// ''
    End Select
End Sub

Note: "received" is spelled this way, not "recieved".

Also, in Server you have:

Dim Port As Integer = 5440

And in Client, you have:

Dim IP As String = "localhost", Port As Integer = 5504

The server is listening on a different port than the client is using.

In client, add code to exit if the client can't connect. Otherwise, the client will keep trying to connect and error messages will keep popping up.

Add the following (to Client):

Dim attemptCount As Integer = 0
Dim maxConnectAttempts As Integer = 4

Then, in Client, add the following code:

attemptCount += 1

If attemptCount < maxConnectAttempts Then
    Connect()
Else
    'close form
    Me.Dispose()
End If

Connect will look like the following:

Sub Connect()
    Try
        t.Connect(IP, Port)
        If t.Connected Then
            t.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
            SendData("Login" & split)
        End If
    Catch ex As Exception
        attemptCount += 1

        MsgBox(ex.Message & " (" & attemptCount & ")")

        If attemptCount < maxConnectAttempts Then
            Connect()
        Else
            'close form
            Me.Dispose()
        End If
    End Try
End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.