gpt4 book ai didi

java.nio.channels.DatagramChannel 基本 UDP RX 客户端连接

转载 作者:行者123 更新时间:2023-11-29 03:36:49 25 4
gpt4 key购买 nike

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

我在调用连接时遇到绑定(bind)异常:

 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)

最佳答案

我以前做过类似的事情,这就是我的代码:

    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

关于java.nio.channels.DatagramChannel 基本 UDP RX 客户端连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com