尝试使用DatagramChanned很好,但它仍然绑定在关闭它之后的地址,并且函数完成执行,如下例所示。
为什么此代码将打印:
电话号码:2
java.net.BindException:已在使用的地址:绑定
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
recever(1);
recever(2);
}
});
}
static void recever(int c) {
try {
DatagramChannel chdata = DatagramChannel.open();
int uport = 3111;
int bufsize = 10;
chdata.configureBlocking(false);
Selector selector = Selector.open();
chdata.bind(new InetSocketAddress(uport));
ByteBuffer bytbuf = ByteBuffer.allocate(bufsize);
chdata.register(selector, SelectionKey.OP_READ);
int th = 0;
int sn;
while (true) {
if (selector.select(1000) == 0){
System.out.println("\nTimeout");
break;
}
Set readyKeys = selector.selectedKeys();
Iterator iterator = readyKeys.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
bytbuf.clear();
chdata.receive(bytbuf);
th++;
bytbuf.flip();
// dealwithincomingbuffer(bytbuf);
}
}
// chdata.bind(null);
chdata.close();
} catch (IOException ex) {
System.out.println("Call num: "+c+" \n "+ex);
}
}
}发布于 2012-12-12 10:54:08
您没有关闭您的套接字在一个最后的块,你根本没有关闭你的选择器。因此,在某些情况下,套接字根本不关闭。
https://stackoverflow.com/questions/13837407
复制相似问题