several clients in java sockets

1

Hi, I would like several clients to connect to my server at the same time

package server.app;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class server {

  public static void run(){

    int puerto = 9000;    
    BufferedReader entrada;
    DataOutputStream salida;
    Socket socket;
    ServerSocket serverSocket;

 try{

       serverSocket = new ServerSocket(puerto);
       socket = serverSocket.accept();
       String thisIp = InetAddress.getLocalHost().getHostAddress();
   System.out.println("IP:"+thisIp);
       while( true){

       }


   }catch(IOException e){};
 }    
}
    
asked by Pacheco 12.10.2018 в 21:10
source

1 answer

0

To do this you have to create a list of sockets where to store each of the connections. Also you have to prepare your code to listen several times.

ArrayList<Socket> sockets = new ArrayList();
try{
   while( true)
   {
     serverSocket = new ServerSocket(puerto);
     socket = serverSocket.accept();
     sockets.add(socket);
     String thisIp = InetAddress.getLocalHost().getHostAddress();
     System.out.println("IP:"+thisIp);
   }


}catch(IOException e){};

If I am not mistaken, the process remains blocked in the serverSocket.accept() until a connection arrives. If my belief is incorrect, add a nullcheck before adding the socket to the list.

    
answered by 08.01.2019 в 10:11