import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
/**
* 非阻塞的Socket链接。<br>
* 可以在链接建立期间做一些别的操作。
*
* @author 赵学庆,Java世纪网(java2000.net)
*
*/
public class SocketNonBlock {
/**
* 创建一个非阻塞的Socket通道。
*
* @param hostName
* 主机
* @param port
* 端口
* @return Socket端口
* @throws IOException
*/
public static SocketChannel createSocketChannel(String hostName, int port)
throws IOException {
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
public static void main(String[] args) {
try {
// 创建链接
SocketChannel sChannel = createSocketChannel("www.java2000.net", 80);
// 可以通过判断是否连接,在链接成功建立前做一些其它的事情
while (!sChannel.finishConnect()) {
System.out.println("waiting....");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(sChannel.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果
waiting....
waiting....
true