提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
演示SocketChannel的异步连接。
import java.net.InetSocketAddress; import java.nio.channels.SocketChannel;/**来 自 nowjava.com**/ public class Main { public static void main(String[] argv) throws Exception { String host = "localhost"; int port = 80; InetSocketAddress addr = new InetSocketAddress(host, port); SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); System.out.println("initiating connection"); sc.connect(addr);/** from 时代Java**/ while (!sc.finishConnect()) { doSomethingUseful(); } System.out.println("connection established"); // Do something with the connected socket // The SocketChannel is still nonblocking sc.close(); }