1

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

1 回答 1

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

于 2013-02-26T02:42:45.320 回答