Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();
   }
like image 261
espcorrupt Avatar asked May 12 '10 18:05

espcorrupt


People also ask

Can multiple sockets connect to the same port?

A connected socket is assigned to a new (dedicated) port, so it means that the number of concurrent connections is limited by the number of ports, unless multiple sockets can share the same port.

Can multiple clients connect to same socket Java?

@asma, yes. Both clients can run on the same machine. Many clients can run on a single machine or multiple machines.

How do you handle multiple clients in socket programming?

A better way to handle multiple clients is by using select() linux command. Select command allows to monitor multiple file descriptors, waiting until one of the file descriptors become active. For example, if there is some data to be read on one of the sockets select will provide that information.


2 Answers

Yes, however only one client will be able to connect per thread execution as written.

You can just put your server run() inside a while true loop to let multiple clients connect. Depending on the executor, they will execute either in series or parallel.

   public class Server extends Thread  
   {  
       ...  
       void run()  
       {  
           while(true){
              // serverSocket on "localhost", 1234  
              Socket clientSock = serverSocket.accept();  
              executor.execute(new ClientWorker(clientSock));  
           }
       }  
   } 
like image 112
patros Avatar answered Sep 22 '22 14:09

patros


As long as you only have one object trying to bind the port for listening, then there's no problem with multiple clients connecting.

like image 44
Jherico Avatar answered Sep 18 '22 14:09

Jherico