title: Java websocket peer-to-peer client socket management
body: <p>I am trying to build peer-to-peer cross platform chat mobile application but I am new to server programming. The server is written in java and I am using spark micro framework for server and <code>org.java_websocket</code> for socket connections I saw some tutorials and have implemented a class that extends <code>WebSocketServer</code> and I do get how the socket will work and the interface methods will get called. But I am unable to figure out a few things:</p>
  
  <ol>
  <li><p>How to manage multiple clients, and how will they connect to my server. Suppose 1000 users want to connect to my server how to implement that.</p></li>
  <li><p>If somehow I managed to connect 1000 users then if user 23 wants to chat with user 52 how will that happen.</p></li>
  <li><p>The code I found on the tutorial requires for me to specify a port so how will I decide which port is free from my server and no other client is connected to that port and according to my knowledge only one socket can be opened on one port so how will I make my server handle millions of users (assuming I get that many).</p></li>
  </ol>
  
  <p>P.S. I am using Tomcat server</p>
  
  <p>The code below is what I found in the tutorial:</p>
  
  <pre><code>public class SocketHandler extends WebSocketServer {
  
      public SocketHandler(int port) throws UnknownHostException{
          super(new InetSocketAddress( port ));
      }
  
      public SocketHandler(InetSocketAddress address) throws UnknownHostException{
          super(address);
      }
  
      @Override
      public void onOpen( WebSocket conn, ClientHandshake handshake ) {
          this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
          System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!" );
      }
  
      @Override
      public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
          this.sendToAll( conn + " has left the room!" );
          System.out.println( conn + " has left the room!" );
      }
  
      @Override
      public void onMessage( WebSocket conn, String message ) {
          this.sendToAll( message );
          System.out.println( conn + ": " + message );
      }
  
      @Override
      public void onWebsocketMessageFragment(WebSocket conn, Framedata frame) {
          super.onWebsocketMessageFragment(conn, frame);
          System.out.println( "received fragment: " + frame );
      }
  }
  </code></pre>