尝试使用java.nio.channels.DatagramChannel执行基本的UDP客户端接收器。我将以下内容放在一起:
DatagramChannel dc = DatagramChannel.open();
dc.setOption(StandardSocketOptions.SO_RCVBUF, Integer.MAX_VALUE);
dc.configureBlocking(true);
int listeningPort = 4445;
dc.connect(new InetSocketAddress(listeningPort));
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(2048);
dc.read(byteBuffer);
我在连接调用时遇到绑定异常:
Exception in thread "main" java.net.BindException: Cannot assign requested address: connect
at sun.nio.ch.Net.connect0(Native Method)
at sun.nio.ch.Net.connect(Unknown Source)
at sun.nio.ch.DatagramChannelImpl.connect(Unknown Source)
我试过切换端口没有运气......有什么想法吗?
我一直关注: http://tutorials.jenkov.com/java-nio/datagram-channel.html
如果我这样做:
dc.socket().bind(new InetSocketAddress(listeningPort));
而不是连接,我得到:
Exception in thread "main" java.nio.channels.NotYetConnectedException
at sun.nio.ch.DatagramChannelImpl.read(Unknown Source)
答案 0 :(得分:4)
之前我做过类似的事情,这就是我的代码:
DatagramChannel datagramChannel = DatagramChannel.open();
DatagramSocket datagramSocket = datagramChannel.socket();
datagramSocket.setReuseAddress(true);
datagramSocket.bind(new InetSocketAddress(HOST, PORT));
datagramSocket.connect(address);
datagramChannel.configureBlocking(false);
datagramChannel.register(selector, SelectionKey.OP_READ);
我的HOST = "localhost"
和PORT = 19000