尝试使用 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)