我在从多播接收字符串时遇到一些问题。这是我第一次在 Java 中使用 UDP 多播。
我正在通过 LAN 制作多客户端应用程序。所以我使用本地 IP 地址。我需要客户端找到服务器的 IP 地址,以便他们可以发送数据、请求等。
我让服务器每 5 秒用他自己的 IP 作为字符串发送一个多播。客户应该能够收到它。问题是他们没有收到任何东西。我正在使用 2 台设备进行测试,所以我不需要使用 localhost。
这是我的一些代码: 服务器端:
公共类 MulticastIpSender 扩展 Thread{
private String serverIp;
private int port;
private String multicastAddress;
private long WAITING_TIME = 5000; // 5 seconden
private DatagramSocket socket;
public MulticastIpSender(String serverIp, int port, String multicastAddress) throws SocketException {
super();
this.serverIp = serverIp;
this.port = port;
this.multicastAddress = multicastAddress;
socket = new DatagramSocket(port);
}
public void run() {
while(true){
try {
byte[] buf = new byte[256];
buf = serverIp.getBytes();
InetAddress group = InetAddress.getByName(multicastAddress);
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
socket.send(packet);
System.out.println("sent IP("+serverIp+") to group("+group+") on port "+port);
sleep(WAITING_TIME);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我把这个方法放在主类中:
private void sendIpAddressToListeners() {
try {
multicastIpSender = new MulticastIpSender(serverIp,PORT,"230.0.0.1");
multicastIpSender.run();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我得到这样的serverIp:
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress addrs[] = InetAddress.getAllByName(hostName);
if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress()) {
myIp = addr.getHostAddress();
}
}
System.out.println ("\nIP = " + myIp);
return myIp;
在这个设备上它给了我 192.168.1.2
客户端:
multicastSocket = new MulticastSocket(PORT);
InetAddress address = InetAddress.getByName(MULTICAST_ADDRESS);
multicastSocket.joinGroup(address);
DatagramPacket serverIpPacket;
byte[] buf = new byte[256];
serverIpPacket = new DatagramPacket(buf, buf.length);
while(receivedIp ==null){
multicastSocket.receive(serverIpPacket);
receivedIp = new String(serverIpPacket.getData(), 0, serverIpPacket.getLength());
System.out.println("received server ip: " + receivedIp);
}
!!服务器和客户端的 PORT = 4445
我希望有人可以帮助我,或者可以解释一个更好的方法来做到这一点。