Tuesday, April 21, 2015

Java Socket - Accepting multiple clients on single port

The concept is simple that after accepting the client on the socket, move that socket on to a separate thread and wait for next client to come to the same port. Code is below

public static void main(String args[]) {
            ServerSocket serverSocket = null;
            Socket socket = null;
            
            try {
                serverSocket = new ServerSocket(1234);
            } catch (IOException e) {
                e.printStackTrace();
                
            }
            while (true) {
                try {
                    socket = serverSocket.accept();
                } catch (IOException e) {
                    System.out.println("I/O error: " + e);
                }
              
                new ClientSocketProcessor(socket).start();
            }

        }


 public class ClientSocketProcessor extends Thread {
            protected Socket clientSocket;
            
            public ClientSocketProcessor(Socket socket) {
                this.clientSocket = socket;
            }
            
            public void run() {
System.out.println("accepted a client socket");
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            System.out.println("created print writer out");
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            
            String inputLine, outputLine;
            
            StringBuffer requestBuffer = new StringBuffer();
            MSIPRequest request = new MSIPRequest();
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
}
            }
        }

References: 
https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
http://stackoverflow.com/questions/10131377/socket-programming-multiple-client-to-one-server

1 comment: