Multiple clients connections with server - 2nd connection crash 1st connection RRS feed

  • Question

  • I am designed a program to have 3 clients connecting with a server. I tried the following code with 3 threads for 3 connections

    However, if the 2nd client connects, the 1st client becomes un-response.  it seems 2nd connection crashes 1st connection.

    any ideas?  Thanks a lot.

    ******************  Server side  ***************************

    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Threading
    Imports System.Configuration

    Module server
        Dim MyIP As String = ConfigurationManager.AppSettings("MyIP").ToString
        Dim serversocket As New TcpListener(System.Net.IPAddress.Parse(MyIP), 8801)
        Dim requestcount As Integer = 0
        Dim clientsocket As New TcpClient

        Sub Main()
            msg("Waiting for connection")
            For i = 1 To 3
                Dim t As Thread = New Thread(New ParameterizedThreadStart(AddressOf AcceptClient))
        End Sub

        Sub AcceptClient(a)
            clientsocket = serversocket.AcceptTcpClient()

            While (True)
                If clientsocket.Connected = True Then
                    Try ' Read from Client
                        Dim networkstream As NetworkStream = clientsocket.GetStream()
                        Dim byesFrom(25) As Byte
                        networkstream.Read(byesFrom, 0, byesFrom.Length)
                        Dim datafromclient As String = System.Text.Encoding.ASCII.GetString(byesFrom)
                        ' Send to Client
                        requestcount = requestcount + 1
                        Dim serverresponse As String = "Server : " + Convert.ToString(requestcount)
                        Dim sendbyes As [Byte]() = System.Text.Encoding.ASCII.GetBytes(serverresponse)
                        networkstream.Write(sendbyes, 0, sendbyes.Length)
                    Catch ex As Exception
                        msg("disconnected : " & a.ToString)
                        Exit While
                    End Try
                End If
            End While
            Dim t As Thread = New Thread(New ParameterizedThreadStart(AddressOf AcceptClient))
        End Sub

        Sub msg(ByVal mesg As String)
            Console.WriteLine(" >> " + mesg)
        End Sub
    End Module

    • Edited by TW88 Friday, November 3, 2017 2:43 AM
    Friday, November 3, 2017 2:39 AM


  • Fixed by defining different clientsocket for different threads


    Sub AcceptClient(abc)
             abc = serversocket.AcceptTcpClient()

    • Marked as answer by TW88 Friday, November 3, 2017 9:27 AM
    Friday, November 3, 2017 9:27 AM