您需要插座。它们充当连接的端点。虽然,您可以使用其他替代方法来阻止
Socket和
ServerSocket实现。
NIO(新IO)使用通道。它允许非阻塞的I / O:
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) { //handle channel } } }}使用选择器 (可选,但推荐)
您可以使用a
Selector在读取/写入/接受之间切换,以仅在无事可做时才进行阻止(以消除过多的CPU使用率)
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); }}SelectionKey支持通过接受via
isAcceptable(),读取via
isReadable()和写入via
isWritable(),因此您可以在同一线程上处理所有3个对象。
这是使用NIO接受连接的基本示例。我强烈建议您多加研究,以更好地了解事物的工作方式。



