New IO Hello Server : ServerSocketChannel « Network « Java Tutorial





import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class MainClass {

  public final static int PORT = 2345;

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

    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    SocketAddress port = new InetSocketAddress(PORT);
    serverChannel.socket().bind(port);

    while (true) {
      SocketChannel clientChannel = serverChannel.accept();

      String response = "Hello " + clientChannel.socket().getInetAddress() + " on port "
          + clientChannel.socket().getPort() + "\r\n";
      response += "This is " + serverChannel.socket() + " on port "
          + serverChannel.socket().getLocalPort() + "\r\n";

      byte[] data = response.getBytes("UTF-8");
      ByteBuffer buffer = ByteBuffer.wrap(data);
      while (buffer.hasRemaining())
        clientChannel.write(buffer);
      clientChannel.close();
    }
  }
}










19.15.ServerSocketChannel
19.15.1.ServerSocketChannel
19.15.2.New IO Hello Server
19.15.3.Test non-blocking accept() using ServerSocketChannel
19.15.4.Accepting a Connection on a ServerSocketChannel
19.15.5.Using a Selector to Manage Non-Blocking Server Sockets
19.15.6.Detecting When a Non-Blocking Socket Is Closed by the Remote Host