Search code examples
javasocketsserversocket

How to write A ServerSocket which accept multiple clicent Socket?


I am working on Socket programming. I have build such a server which should accept multiple Clients. Here I have particular num of clients , clients keeps on sending msg to Server every 10sec , Server has to process it.The problem I am having is I am unable to connect multiple Server and here a single client is a continuous running programm in while(true) So if one client Sends a request another client can not connect . Here is my Program.

Server

public class SimpleServer extends Thread {

private ServerSocket serverSocket = null;
private Socket s1 = null;

SimpleServer() {
    try {
        serverSocket = new ServerSocket(1231);
        this.start();
    } catch (IOException ex) {
        System.out.println("Exception on new ServerSocket: " + ex);
    }
}

public void run() {
    while (true) {
        try {

            System.out.println("Waiting for connect to client");
            s1 = serverSocket.accept();
            System.out.println("Connection received from " + s1.getInetAddress().getHostName());

            InputStream s1In = s1.getInputStream();
            DataInputStream dis = new DataInputStream(s1In);

            String st = dis.readUTF();
            System.out.println(st);
            s1In.close();
            dis.close();
            s1.close();
           // throw new ArithmeticException();

        } catch (IOException ex) {
            Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
        }
         catch (Exception e) {
             System.out.println("Exceptiopn: "+e);
        }

    }
}

public static void main(String args[]) throws IOException {

    new SimpleServer();
 }
}

Server is working fine but I am not able to write Client program which shoud run in while(true) loop for sending msg to Server and allow other client also connect to Server. but for a single client I write like this ,

public class SimClient extends Thread {

private Socket s1 = null;

SimClient() {
    //this.start();

}

public void run() {
    int i=0;
    try {
        s1 = new Socket("localhost", 1231);
    } catch (IOException ex) {
        Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
    }
   // while (i<10) {
        try {
            // Open your connection to a server, at port dfg1231


            OutputStream s1out = s1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(s1out);

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             System.out.println("Enter Data from Client:");
            String s = br.readLine();
            dos.writeUTF(s);
            dos.flush();
            s1out.close();
            dos.close();
           // s1.close();
            i++;

        } catch (IOException ex) {

           //ex.printStackTrace();
            System.out.println("Exception in While: "+ex.getMessage());
        }


    //}
}

public static void main(String args[]) throws IOException {

   SimClient s= new SimClient();
   s.start();
}


 }

So can any one help me to write client program. its a great help for me.


Solution

  • just as you have a Thread for the ServerSocket, you need to create a Thread for every Socket returned by serverSocket.accept() , then it loops back around immediately to block and wait to accept another Socket. Make a class called SocketHander which extends Thread and accepts a Socket in the constructor.

    public class SocketHandler extends Thread {
        private Socket socket;
    
        public SocketHandler(Socket socket) {
            this.socket = socket;
        }
    
        public void run() {
            // use the socket here
        }
    }
    

    and back in the ServerSocket handler...

    for (;;) {
        SocketHandler socketHander = new SocketHandler(serverSocket.accept());
        socketHander.start();
    }