我想,如果我理解了这个问题,如果要发送的数据对于所有客户端都是相同的,那么就不需要为每个客户端创建单独的数据包,只需创建一个数据包并更改其地址(如有必要,还可以更改端口)像这样会这样做:
/**
* Send a DatagramPacket to all addresses in hosts.
* @param socket
* A created DatagramSocket
* @param hosts
* Array of strings containing the hosts to send the packet,
* each one can be either a host name or a dotted IP address.
* @param port
* The port the clients are listening
* @param data
* Data to send
* @return
* Number of packets sent.
*/
int sendPackets(DatagramSocket socket, String[] hosts, int port, byte[] data)
{
if (hosts.length > 0)
try
{
int ret=0;
DatagramPacket packet = new DatagramPacket(data, data.length);
packet.setPort(port);
for (int i = 0; i < hosts.length; i++)
{
try
{
packet.setAddress(InetAddress.getByName(hosts[i]));
socket.send(packet);
ret++;
}
catch (Exception e)
{
Log.e("SEND:", "Error sending to host: " + hosts[i]);
e.printStackTrace();
}
}
return ret;
}
catch (Exception e)
{
e.printStackTrace();
}
return 0;
}
您可以像这样使用该功能:
try {
DatagramSocket socket = new DatagramSocket();
byte[] data = "This is a test message.\n".getBytes();
sendPackets(socket, new String[] { "192.168.1.10", "192.168.1.12", "192.168.1.54" }, 2020, data);
}
catch(Exception e){}