[英]Asynchronous UDP how to get ip and port from client in java?
This is my code: 这是我的代码:
channel = DatagramChannel.open();
socket = channel.socket();
channel.configureBlocking(false);
socket.bind(new InetSocketAddress(3000));
selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);
ByteBuffer buffer = ByteBuffer.allocate(65536);
while(true)
{
if(selector.select()>0)
{
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator iterator = selectionKeys.iterator();
while(iterator.hasNext())
{
SelectionKey key = (SelectionKey)iterator.next();
iterator.remove();
InetSocketAddress isa = (InetSocketAddress) channel.getRemoteAddress();
if(key.isReadable())
{
System.out.print(isa.getAddress().getHostAddress()+":"+isa.getPort());
}
}
}
}
the isa is null.I want to get the DatagramPack SocketAddress like socket.receive(DatagramPack); isa是null。我想得到像socket.receive(DatagramPack)的DatagramPack SocketAddress; but i dont know channel how to get it. 但我不知道渠道如何得到它。 Use Channel.getSocketAddress() retun Null. 使用Channel.getSocketAddress()重新调整Null。
UDP is a connectionless protocol, so you will not be able to find the remote address of the channel , since there is no such thing. UDP是一种无连接协议,因此您将无法找到该通道的远程地址,因为没有这样的东西。 Once you open a UDP port for listening, everybody can send you messages, without establishing a direct connection. 一旦打开UDP端口进行监听,每个人都可以向您发送消息,而无需建立直接连接。 Every message you receive can potentially come from a different sender. 您收到的每条消息都可能来自不同的发件人。
What you can do is to retrieve the remote address of the message . 您可以做的是检索邮件的远程地址。 Check the DatagramChannel.receive()
method: it will fill the buffer with the message, and return the address of the sender of that particular message. 检查DatagramChannel.receive()
方法:它将使用消息填充缓冲区,并返回该特定消息的发送方的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.