Using select( ) to service multiple channels - Java Network

Java examples for Network:Socket Channel

Introduction

Simple echo-back server which listens for incoming stream connections and echoes back whatever it reads.

A single Selector object is used to listen to the server socket to accept new connections and all the active socket channels.

Demo Code

 
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Main {
  public static void main(String[] argv) throws Exception {
    int port = 5555;
    System.out.println("Listening on port " + port);
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    ServerSocket serverSocket = serverChannel.socket();
    Selector selector = Selector.open();
    serverSocket.bind(new InetSocketAddress(port));
    serverChannel.configureBlocking(false);
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      int n = selector.select();
      if (n == 0) {
        continue; // nothing to do
      }/*w ww. jav a 2 s  .  c  om*/
      Iterator it = selector.selectedKeys().iterator();
      while (it.hasNext()) {
        SelectionKey key = (SelectionKey) it.next();
        if (key.isAcceptable()) {
          ServerSocketChannel server = (ServerSocketChannel) key.channel();
          SocketChannel channel = server.accept();
          registerChannel(selector, channel, SelectionKey.OP_READ);
          channel.write(ByteBuffer.wrap("Hi there!\r\n".getBytes()));
        }
        if (key.isReadable()) {
          readDataFromSocket(key);
        }
        it.remove();
      }
    }
  }
  protected static void registerChannel(Selector selector, SelectableChannel channel,
      int ops) throws Exception {
    if (channel == null) {
      return; // could happen
    }
    channel.configureBlocking(false);
    channel.register(selector, ops);
  }
  protected static void readDataFromSocket(SelectionKey key) throws Exception {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    int count;
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    buffer.clear(); // Empty buffer
    while ((count = socketChannel.read(buffer)) > 0) {
      buffer.flip(); // Make buffer readable
      while (buffer.hasRemaining()) {
        socketChannel.write(buffer);
      }
      buffer.clear(); // Empty buffer
    }
    if (count < 0) {
      socketChannel.close();
    }
  }
}

Result


Related Tutorials