Java examples for Network:Socket Channel
A nonblocking accept( ) with ServerSocketChannel
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class Main { public static void main(String[] argv) throws Exception { int port = 1234; // default ByteBuffer buffer = ByteBuffer.wrap("this is a test".getBytes()); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(port)); ssc.configureBlocking(false);/*from w w w . ja va 2s . c om*/ while (true) { System.out.println("Waiting for connections"); SocketChannel sc = ssc.accept(); if (sc == null) { Thread.sleep(2000); } else { System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress()); buffer.rewind(); sc.write(buffer); sc.close(); } } } }