【发布时间】:2014-12-10 08:12:10
【问题描述】:
我的网络上有多个服务器,它们都发送广播消息。使用以下客户端,我试图捕获来自所有服务器的所有广播消息。发送部分工作正常(未包含在这篇文章中),但我的接收部分不工作......我不断收到“SocketException:不是多播地址”,我做错了什么?
public static String[] capture(int port) { // port is always 63332
ArrayList<String> clients = new ArrayList<>();
InetAddress address = Utilities.getBroadcastAddress(); // I get "/192.168.2.255" here
MulticastSocket socket = null;
try {
socket = new MulticastSocket(port);
socket.setSoTimeout(2000);
socket.joinGroup(address); // this part throws the exception
DatagramPacket packet;
byte[] packetContent;
while (true) {
packetContent = new byte[1024];
packet = new DatagramPacket(packetContent, packetContent.length);
try {
socket.receive(packet);
String client = packet.getAddress() + ":" + packet.getPort();
clients.add(client);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(socket != null) {
try {
socket.leaveGroup(address);
} catch(IOException e) {
e.printStackTrace();
}
socket.close();
}
return clients.toArray(new String[clients.size()]);
}
【问题讨论】:
标签: java sockets multicast datagram