我编写了两个小应用程序(一个客户端和一个服务器)来测试 UDP 通信,我发现它们之间的“连接”(是的,我知道,没有真正的连接)会无缘无故地丢失。
我知道 UDP 是一个不可靠的协议,但这里的问题似乎不是丢包,而是应用程序之间的通信通道丢失。
这是客户端应用程序代码:
class ClientProgram
{
static void Main(string[] args)
{
var localEP = new IPEndPoint(GetIPAddress(), 0);
Socket sck = new UdpClient(localEP).Client;
sck.Connect(new IPEndPoint(IPAddress.Parse("[SERVER_IP_ADDRESS]"), 10005));
Console.WriteLine("Press any key to request a connection to the server.");
Console.ReadLine();
// This signals the server this clients wishes to receive data
SendData(sck);
while (true)
{
ReceiveData(sck);
}
}
private static void ReceiveData(Socket sck)
{
byte[] buff = new byte[8];
int cnt = sck.Receive(buff);
long ticks = BitConverter.ToInt64(buff, 0);
Console.WriteLine(cnt + " bytes received: " + new DateTime(ticks).TimeOfDay.ToString());
}
private static void SendData(Socket sck)
{
// Just some random data
sck.Send(new byte[] { 99, 99, 99, 99 });
}
private static IPAddress GetIPAddress()
{
IPHostEntry he = Dns.GetHostEntry(Dns.GetHostName());
if (he.AddressList.Length == 0)
return null;
return he.AddressList
.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip))
.FirstOrDefault();
}
}
这是服务器应用程序代码:
class ServerProgram
{
private static int SLEEP = 5;
static void Main(string[] args)
{
// This is a static IP address
var localEP = new IPEndPoint(GetIPAddress(), 10005);
Socket sck = new UdpClient(localEP).Client;
// When this methods returs, a client is ready to receive data
var remoteEP = ReceiveData(sck);
sck.Connect(remoteEP);
while (true)
{
SendData(sck);
System.Threading.Thread.Sleep( ServerProgram.SLEEP * 1000);
}
}
private static EndPoint ReceiveData(Socket sck)
{
byte[] buff = new byte[8];
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int cnt = sck.ReceiveFrom(buff, ref clientEP);
Console.WriteLine(cnt + " bytes received from " + clientEP.ToString());
return (IPEndPoint)clientEP;
}
private static void SendData(Socket sck)
{
DateTime n = DateTime.Now;
byte[] b = BitConverter.GetBytes(n.Ticks);
Console.WriteLine("Sending " + b.Length + " bytes : " + n.TimeOfDay.ToString());
sck.Send(b);
}
private static IPAddress GetIPAddress()
{
// Same as client app...
}
}
(这只是测试代码,不要关注无限循环或缺乏数据验证)
问题是在发送了几条消息后,客户端停止接收它们。服务器继续发送,但客户端卡在sck.Receive(buff)
. 如果我将 SLEEP 常量更改为高于 5 的值,则“连接”大部分时间在 3 或 4 条消息后丢失。
我可以确认客户端机器在连接丢失时没有收到任何数据包,因为我使用 Wireshark 监控通信。
服务器应用程序在直接连接到 Internet 的服务器上运行,但客户端是本地网络中的一台机器,位于路由器后面。他们都没有运行防火墙。
有谁知道这里会发生什么?
谢谢!
编辑 - 附加数据:
我在同一网络中的多台机器上测试了客户端应用程序,但连接总是丢失。我还在其他路由器后面的其他网络中测试了客户端应用程序,那里没有问题。我的路由器是 Linksys RV042,从来没有任何问题,事实上,这个应用程序是唯一一个有问题的应用程序。