Java sockets: multiple client threads on same port on same machine?

Posted by espcorrupt on Stack Overflow See other posts from Stack Overflow or by espcorrupt
Published on 2010-05-12T18:26:56Z Indexed on 2010/05/12 18:34 UTC
Read the original article Hit count: 227

Filed under:
|
|
|

I am new to Socket programming in Java and was trying to understand if the below code is not a wrong thing to do. My question is:

Can I have multiple clients on each thread trying to connect to a server instance in the same program and expect the server to read and write data with isolation between clients"

public class Client extends Thread
{
    ...
    void run()
    {
        Socket socket = new Socket("localhost", 1234);
        doIO(socket);  
    }
}

public class Server extends Thread
{
    ...
    void run()
    {
        // serverSocket on "localhost", 1234
        Socket clientSock = serverSocket.accept();
        executor.execute(new ClientWorker(clientSock));
    }
}

Now can I have multiple Client instances on different threads trying to connect on the same port of the current machine?

For example,

   Server s = new Server("localhost", 1234);
   s.start();
   Client[] c = new Client[10];
   for (int i = 0; i < c.length; ++i)
   {
        c.start();
   }

© Stack Overflow or respective owner

Related posts about java

Related posts about port