慕粉4167745
JAVA 7到来了,所以新的答案是带有Future类的NIO.2。范例:在服务器端:final AsynchronousServerSocketChannel serverSocket= AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("127.0.0.1", 2587)); // Listening on port 2587 for client connectionFuture future= serverSocket.accept();final AsynchronousSocketChannel clientSocket= future.get(); // now it's blocking, useful: future.isDone() and .isCancelled()//Do whatever you want ..InputStream stream = Channels.newInputStream(clientSocket) (...)在客户端:AsynchronousSocketChannel clientChannel = AsynchronousSocketChannel.open();Future connected = localSocket.connect(ourServerSocketAddress);// later: if(future.isDone())connected.get();//Send somethingOutputStream os = Channels.newOutputStream(clientChannel );os.write (...)更新: 如果可以使用actor模型,那么AKKA TCP IO会更好。