title: Java multi client server with selectors
body: <p>ihave read that it is possible to create a multi client server with just one thread using the selector and channels.i made a quick sketch to test out the functionality and it seems it can only process the socket data per connection...i mean the first client connected and the server is waiting to packets from it if another client connects it doesnt processes it... any help?as a end result i wanna my server to listen to multiple clients each client will be able to connect send and recieve data to/from the server so if it sends the server writes: Client[num] sent this data"data'</p>
  
  <p>heres the code:</p>
  
  <pre><code>public static void Startnio() throws Exception
      {
          ServerSocketChannel ServerChannel = ServerSocketChannel.open();
          ServerChannel.configureBlocking(false);
          ServerSocket Server = ServerChannel.socket();
          Server.bind(new InetSocketAddress(port));
          Selector selector = Selector.open();
          ServerChannel.register(selector, SelectionKey.OP_ACCEPT);
          System.out.println("Server began listening on port: " + port);
  
          while (true)
          {
              int num = selector.select();
              if (num == 0)
              {
                  continue;
              }
              Set keys = selector.selectedKeys();
              Iterator it = keys.iterator();
              while (it.hasNext())
              {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() &amp; SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT)
                  {
                      Socket Client = Server.accept();
                      count++;
                      System.out.println("Client Connected...." + "you have " + count + " clients connected");
                      SocketChannel ClientChannel = Client.getChannel();
                      ClientChannel.configureBlocking(false);
                      ClientChannel.register(selector, SelectionKey.OP_READ);//read incoming stream
                  }
                  else
                  {
                      if ((key.readyOps() &amp; SelectionKey.OP_READ) == SelectionKey.OP_READ)
                      {
                          SocketChannel Client = null;
                          Client = (SocketChannel) key.channel();
                          client=Client;
                          ReadClientStream();
                      }
                  }
  
  
  
  
              }
          }
      }
  </code></pre>
  
  <p>the read client stream is just some standard bytebuffer.</p>