我正在使用UDP开发聊天应用程序。获取另一个对等端口号时遇到问题。我可以获得对等方的主机地址,但不能获得响应/请求来自的端口。是否可以获取向我发送请求/响应的对等端口号。
这是我的代码:
private Thread bcastListen = new Thread(PeerDiscovery.class.getSimpleName()
+ " broadcast listen thread") {
@Override
public void run() {
try {
byte[] buffy = new byte[5];
buffy[2] = (byte) 4000;
DatagramPacket rx = new DatagramPacket(buffy, buffy.length);
while (!shouldStop) {
try {
buffy[0] = 0;
bcastSocket.receive(rx);
int recData = decode(buffy, 1);
if (buffy[0] == QUERY_PACKET && recData == group) {
byte[] data = new byte[5];
data[0] = RESPONSE_PACKET;
encode(peerData, data, 1);
DatagramPacket tx
= new DatagramPacket(data, data.length, rx.getAddress(), port);
System.out.println(peerData);
lastResponseDestination = rx.getAddress();
bcastSocket.send(tx);
} else if (buffy[0] == RESPONSE_PACKET) {
if (responseList != null && !rx.getAddress().equals(lastResponseDestination)) {
synchronized (responseList) {
responseList.add(new Peer(rx.getAddress(), rx.getPort())); //here am trying to get the port of the host which the response came from (Doesn't work)
}
}
}
} catch (SocketException se) {
System.out.println("Some exception");
}
}
bcastSocket.disconnect();
bcastSocket.close();
}
感谢您的时间。
答案 0 :(得分:1)
传入数据报的源地址可通过DatagramPacket.getPort()
获得。
但不是端口
我不知道为什么不。你考虑过咨询Javadoc吗?
注意,做你正在做的事情的简单方法就是发送收到的数据包。无需再构建另一个。
bcastSocket.disconnect();
你还没有调用bcastSocket.connect()
,所以这行代码是徒劳的。删除它。