81,092
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
public class SocketNonBlock {
public static SocketChannel createSocketChannel(String hostName, int port)
throws IOException {
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
sChannel.connect(new InetSocketAddress(hostName, port));
sChannel.finishConnect();
return sChannel;
}
public static void main(String[] args) {
try {
// 创建链接
SocketChannel sChannel = createSocketChannel("feeds.delicious.com", 80);
ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
// 可以通过判断是否连接,在链接成功建立前做一些其它的事情
while (!sChannel.finishConnect()) {
System.out.println("等待非阻塞连接建立....");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(sChannel.isConnected());
} catch (Exception e1) {
}
}
}