我必须在Android中发送UDP广播。我总是在socket.send(数据包)中获得 java.io.IOException:无效参数。 创建套接字对象时,我有时会得到已使用的地址异常
private void setBroadCastMessage() {
final int udpPortNumber = 6000;
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getActiveNetworkInfo();
if (mWifi.getType() == ConnectivityManager.TYPE_WIFI) {
if (mWifi.isConnected()) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
try {
InetAddress address;
address=InetAddress.getByName("255.255.255.255");
DatagramSocket datagramSocket = new DatagramSocket(udpPortNumber,address);
messageBroadCast(datagramSocket,address);
} catch (SocketException e) {
e.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
thread.start();
}
}
}
public void messageBroadCast(DatagramSocket socket, InetAddress address)
{
String data="This is my discovery request";
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
address, 6000);
try {
socket.send(packet);
LogUtils.errorLog("Address :"," "+address);
LogUtils.errorLog("Send String:"," "+data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:-1)
无法将此作为评论发布,但这里是我使用过的代码,它与您的代码非常相似。
如果您还有其他问题,请尝试此操作并添加堆栈跟踪。
我使用它成功地广播到IP地址“255.255.255.255”
private void sendToIP(String ip, int port, String message) {
try {
DatagramSocket socket = new DatagramSocket();
byte[] sendData = message.getBytes();
InetAddress IPAddress = InetAddress.getByName(ip);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
socket.send(sendPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:-1)
如果您想播放,可能需要致电DatagramSocket.setBroadcast(true)
。但是你在这里尝试的类型的广播已被弃用了20多年。