Multiple socket clients

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Markgoldin

    Multiple socket clients

    Here is code I am using to create a socket listener:
    public void Run()

    {

    go = true;

    Random rand = new Random();

    // Buffer for reading data

    Byte[] bytes = new Byte[1024];

    String data = null;

    while (go)

    {

    TcpClient tcpc = FromAnotherClas s.tcpl.AcceptTc pClient(); //accept
    connection

    data = null;

    // Get a stream object for reading and writing

    NetworkStream stream = tcpc.GetStream( );

    // Loop to receive all the data sent by the client.

    int i;

    while ((i = stream.Read(byt es, 0, bytes.Length)) != 0)

    {

    // Translate data bytes to a ASCII string.

    data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);

    // Process the data sent by the client.

    if (data != "")

    {

    System.Console. WriteLine(data) ;

    }

    }

    Thread.Sleep(10 00 + rand.Next(2000) );

    }

    }

    My question is can this code handle connections from multiple clients?

    Or should I have a separate listener for each client?



    Thanks for help.


  • Ignacio Machin ( .NET/ C# MVP )

    #2
    Re: Multiple socket clients

    >
    My question is can this code handle connections from multiple clients?
    >
    Or  should I have a separate listener for each client?
    You need to have one thread listening for connection, and when a
    connection is received a new thread is spawned to handle it.

    I have posted similar code in the past, it's very easily done with a
    Sync Queue.

    Look in the archive or post back if you do not find my old posts

    Comment

    • Ignacio Machin ( .NET/ C# MVP )

      #3
      Re: Multiple socket clients

      found the post:

      while(true)
      {
      Socket s = listener1.Accep tSocket();
      syncedQueue.Enq ueue( s );
      new Thread( new ThreadStart( workerMethod) ).Start();
      }

      workerMethod()
      {
      Socket s = syncedQueue.Deq ueue();
      }

      You have to use a synced queue though:

      syncedqueue = Queue.Synchoniz e( new Queue() );

      Comment

      • Markgoldin

        #4
        Re: Multiple socket clients

        This is a bit above my head. How do I pull data from it?


        "Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin @gmail.comwrote in
        message
        news:6494cc59-2b1d-42d0-aa69-8ee353ab0de6@l4 2g2000hsc.googl egroups.com...
        found the post:
        >
        while(true)
        {
        Socket s = listener1.Accep tSocket();
        syncedQueue.Enq ueue( s );
        new Thread( new ThreadStart( workerMethod) ).Start();
        }
        >
        workerMethod()
        {
        Socket s = syncedQueue.Deq ueue();
        }
        >
        You have to use a synced queue though:
        >
        syncedqueue = Queue.Synchoniz e( new Queue() );

        Comment

        Working...