You need sockets. They serve as connection endpoints . Although you can use alternatives to blocking Socketand implementations ServerSocket. NIO (New IO) uses channels. It allows non-blocking input-output:
class Server {
public static void main(String[] args) throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
while(true) {
SocketChannel sc = ssc.accept();
if(sc != null) {
}
}
}
}
Using selector
Or you can use Selectorto switch between read / write / receive to allow locking only when theres nothing to do (to remove excessive CPU usage)
class Server {
private static Selector selector;
public static void main(String[] args) throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
Selector selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
selector.select();
while(selector.iterator().hasNext()) {
SelectionKey key = selector.iterator().next();
if(key.isAcceptable()) {
accept(key);
}
}
}
}
private static void accept(SelectionKey key) throws Exception {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel sc = channel.accept();
sc.register(selector, OP_READ);
}
}
SelectionKeyIt supports receiving through isAcceptable(), reading through isReadable()and writing through isWritable(), so you can handle all 3 in one thread.
NIO. , , .