【发布时间】:2015-12-01 15:50:59
【问题描述】:
大家好,我正在用 C# 开发一个带有服务器和许多客户端的应用程序,我需要它们进行通信,特别是服务器必须向所有客户端发送一个数据包,这发生在随机时间(它只发送数据包当另一个程序发送我捕获的信号时)。我不想使用 TCP,因为这必须尽可能快,而且我有很多客户端(可能超过一千个)。
我尝试了一些使用 UDP 的解决方案,使用广播和多播,还使用循环将数据包单独发送给所有这些解决方案。我用 1 个服务器和 2 个客户端对其进行了测试,当它们在同一台机器上时,这两个解决方案都可以正常工作,但是当我把它放在互联网上(一台机器上的服务器和不同网络中另一台机器上的客户端)时,程序没有不再工作了,客户什么也收不到。
发件人:
private void send(string packet){
/* code to get the key to encript the data */
byte[] bytes = Encryptor.EncryptString(packet, key);
query = "SELECT ip FROM utenti WHERE ID <> 2";
List<string> ips = SelectIPs(query);
foreach (string ip in ips){
if (ip == "")
continue;
UdpClient client = new UdpClient();
IPAddress address = IPAddress.Parse(ip);
IPEndPoint ipEndPoint = new IPEndPoint(address, 16759);
client.Send(bytes, bytes.Length, ipEndPoint);
client.Close();
}
}
接收者:
private void receive(string packet){
receivingUdpClient = new UdpClient(16759);
RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("185.43.209.118"), 0);
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
/* code to get the key to decrypt */
string returnData = Encryptor.DecryptString(receiveBytes, key);
Console.WriteLine(returnData);
return;
}
我在发送中发布了带有循环的解决方案,但我也尝试了广播和多播。
有什么建议可以做什么以及为什么如果它们在不同的机器上我没有收到任何东西?
【问题讨论】: