这是我的主要方法:
public void broadcastName(final String name, final InetAddress broadcastIP) {
// Broadcasts the name of the device at a regular interval
System.out.println("Broadcasting started!");
Thread broadcastThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String request = "ADD:"+name;
byte[] message = request.getBytes();
DatagramSocket socket = new DatagramSocket();
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(message, message.length, broadcastIP, BROADCAST_PORT);
while(BROADCAST) {
System.out.println("socket: "+socket);
socket.send(packet);
System.out.println("Broadcast packet sent: " + packet.getAddress().toString());
Thread.sleep(BROADCAST_INTERVAL);
}
System.out.println("Broadcaster ending!");
socket.disconnect();
socket.close();
return;
}
catch(SocketException e) {
System.out.println("SocketException in broadcast: " + e);
System.out.println("Broadcaster ending!");
return;
}
catch(IOException e) {
System.out.println("IOException in broadcast: " + e);
System.out.println("Broadcaster ending!");
return;
}
catch(InterruptedException e) {
System.out.println("InterruptedException in broadcast: " + e);
System.out.println("Broadcaster ending!");
return;
}
}
});
broadcastThread.start();
}
我在while(BROADCAST)行之后立即进入socket.send(packet)时,始终遇到此错误。
Exception in thread "Thread-1" java.lang.NullPointerException: null address || null buffer
at java.net.DualStackPlainDatagramSocketImpl.send(Unknown Source)
at java.net.DatagramSocket.send(Unknown Source)
at application.ContactManager$2.run(ContactManager.java:103)
at java.lang.Thread.run(Unknown Source)
我检查以确保套接字和数据包都不为空!还有什么罪魁祸首?
该错误消息的含义是什么?
编辑
我正在Windows便携式计算机上从Eclipse运行此代码。
我检索IP地址并设置broadcastIP的方式是这样的:
private static InetAddress getBroadcastIp() {
// Function to return the broadcast address, based on the IP address of the device
try {
String addressString = InetAddress.getLocalHost().toString();
InetAddress broadcastAddress = InetAddress.getByName(addressString);
return broadcastAddress;
}
catch(UnknownHostException e) {
System.out.println("UnknownHostException in getBroadcastIP: " + e);
return null;
}
}
最佳答案
将解决方案放在这里,就像@WayWay在评论中提到的那样:
尝试获取IP地址时,当前代码无法正常运行,因为.toString()
的结果无法解析,因此,请改用:
String addressString = InetAddress.getLocalHost().toString();
InetAddress broadcastAddress = InetAddress.getByName(addressString);
您应该尝试使用以下方法检索它:
InetAddress.getLocalHost().getHostAddress();
这样,您将获得广播所需的正确
InetAddress
。