tcpclient server in async mode accepting multiple clients and on multiple ports

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Veeraraghavan
    New Member
    • Jan 2010
    • 2

    tcpclient server in async mode accepting multiple clients and on multiple ports

    Hi All,

    I am developing a client server communication using system.net.sock et and I am finding it very difficult to get a solution for this. I started with single port communication with single client and as I was asked to develop to listen on multiple ports handling multiple clients, I am stuck with out a solution. The below is what could end up doing any help to solve the problem will be very much appreciated.

    Below is the code I tried but it does not allow a single client on multiple requests.
    Code:
    Class MyTcpListener
        Public Shared stream As NetworkStream
        Public Shared Sub Main()
            Dim port As Int32 = 1006
            Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
            Dim server As TcpListener = Nothing
            server = New TcpListener(localAddr, port)
            server.Start()
            DoBeginAcceptSocket(server)
        End Sub 'Main
        ' Thread signal.
        Public Shared clientConnected As New ManualResetEvent(False)
    
    
        ' Accept one client connection asynchronously.
        Public Shared Sub DoBeginAcceptSocket(ByVal listener As TcpListener)
            ' Set the event to nonsignaled state.
            clientConnected.Reset()
    
            ' Start to listen for connections from a client.
            Console.WriteLine("Waiting for a connection...")
    
            ' Accept the connection. 
            ' BeginAcceptSocket() creates the accepted socket.
    
            listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf DoAcceptSocketCallback), listener)
            ' Wait until a connection is made and processed before 
            ' continuing.
    
            clientConnected.WaitOne()
        End Sub 'DoBeginAcceptSocket
    
    
        ' Process the client connection.
        Public Shared Sub DoAcceptSocketCallback(ByVal ar As IAsyncResult)
            ' Get the listener that handles the client request.
            Dim returnvalue As IAsyncResult
            Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
            Dim client As Socket
            client = listener.BeginAcceptSocket(New AsyncCallback(AddressOf DoAcceptSocketCallback), listener)
            ' End the operation and display the received data on the
            'console.
            Dim bytes(1024) As Byte
    
            returnValue = stream.BeginRead(bytes, 0, bytes.Length, New AsyncCallback(AddressOf myReadCallBack), stream)
            ' Process the connection here. (Add the client to a 
            ' server table, read data, etc.)
            Console.WriteLine("Client connected completed")
            Dim clientSocket As TcpClient = listener.EndAcceptTcpClient(ar)
            ' Signal the calling thread to continue.
            clientConnected.Set()
        End Sub 'DoAcceptSocketCallback
    
        Public Shared Sub myReadCallBack(ByVal ar As IAsyncResult)
    
            Dim myNetworkStream As NetworkStream = CType(ar.AsyncState, NetworkStream)
            Dim myReadBuffer(1024) As Byte
            Dim myCompleteMessage As [String] = ""
            Dim numberOfBytesRead As Integer
    
            numberOfBytesRead = myNetworkStream.EndRead(ar)
            myCompleteMessage = [String].Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
    
            ' message received may be larger than buffer size so loop through until you have it all.
            While myNetworkStream.DataAvailable
    
                myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, New AsyncCallback(AddressOf myReadCallBack), myNetworkStream)
            End While
    
    
            ' Print out the received message to the console.
            Console.WriteLine(("You received the following message : " + myCompleteMessage))
        End Sub 'myReadCallBack
    
    
    End Class 'MyTcpListener
    In deep trouble
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      I recommend implementing a class that manages the connection alone that is separate from the class listens for new connections. The class that listens for connections will have to have a collection of classes that manages the connection so that when a new connection is made it can add a new connection to the collection.

      For example, you would have to implement a class...let's call it "AsyncClientCon nection" that manages the connection. This class manages the asynchronous socket connection logic. It is responsible for sending and receiving data from the a the client that the connection is for.

      You would also have to implement a class that manages the connections...l et's call it the "SocketServerMa nager". This class manages the connected AsyncClientConn ections. It has a collection (an array, or list of) of AsyncClientConn ections. The SocketServerMan ager accepts incoming asynchronous socket connections and creates new AsyncClientConn ections (that manages the connection) for each connection and adds it to the collection. It also removes any AsyncClientConn ections that are no longer connected every so often to clean up unused resources.

      -Frinny

      Comment

      • Veeraraghavan
        New Member
        • Jan 2010
        • 2

        #4
        Thanks Frinny,

        I finally found the solution The server now has 2 classes one class handling new client requests and in that class we call another class which connects already connected client.

        Both the classes have methods which run with infinite loops which makes handling any number of requests from multiple clients using the same port

        thanks again

        Comment

        • oghenez
          New Member
          • Jun 2015
          • 1

          #5
          can you send me the code, i need your help. pls post here or send to oghenez @ gmail dot com

          Comment

          Working...