大家。我有关于套接字使用的问题。虽然看起来很简单,但我无法管理它。所以问题听起来:我可以只使用一个套接字将数据包发送到多个客户端吗?
ds1 = new DatagramSocket();
dp1 = new DatagramPacket(packet, packet.length, InetAddress.getByName(address1), port);
dpto2 = new DatagramPacket(packet, packet.length, InetAddress.getByName(address2), port);
dpto3 = new DatagramPacket(packet, packet.length, InetAddress.getByName(address3), port);**
此处的地址1,地址2和地址3不同。我想在一个程序运行中连接到多个客户端并向它们发送UDP数据包。我还没有测试过,只是想得到一些关于如何做的建议。
任何帮助将不胜感激......
答案 0 :(得分:2)
DatagramSocket
答案 1 :(得分:0)
我认为,如果我理解了这个问题,如果要发送的数据对于所有客户端都是相同的,那么就不需要为每个客户端创建单独的数据包,只需创建一个数据包并更改其地址(如果需要,还可以更改端口) 像这样的东西会这样做:
/**
* 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){}