我目前正在尝试创建UDP客户端/服务器。这很简单,有一个发送函数,它发送一个字节,然后客户端立即响应一条消息,其中包含我正在侦听的信息
我在接收数据时遇到了麻烦。我一直都在接收数据,并且收到的包裹确实有正确的长度,但是消息似乎混乱了。
SendAndReceive函数在10秒计时器上。
编辑:如果我每次调用SendAndReceive函数时都重新创建MyUdpClient,则它将正常工作,并且程序包的顺序不正确。
这是我的代码:
private void SendAndReceive(object sender = null, ElapsedEventArgs e = null)
{
ClientEndpoint = new IPEndPoint(IPAddress.Parse(IP), Port);
// Works if i recreate MyUdpClient...
MyUdpClient = new UdpClient();
MyUdpClient.ExclusiveAddressUse = false;
MyUdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
MyUdpClient.Send(InfoPacket, InfoPacket.Length, ClientEndpoint);
try
{
MyUdpClient.BeginReceive(new AsyncCallback(ReceiveMessages), null);
}
catch (Exception exception)
{
Console.WriteLine($"Exception: {exception.ToString()}");
}
}
public void ReceiveMessages(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, Port);
byte[] receivedPacket = MyUdpClient.EndReceive(res, ref RemoteIpEndPoint);
var ipAddress = RemoteIpEndPoint.Address.ToString();
MyUdpClient.BeginReceive(new AsyncCallback(ReceiveMessages), null);
// This is for debugging.
string receivedTime = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine($"[{receivedTime}]{ipAddress} {receivedPacket.Length} {Encoding.Default.GetString(receivedPacket)}");
// Process Data Further
...
}
常见的输出通常是这样的:
[18.29.30]172.20.55.32 475 a
[18.29.30]172.20.55.10 455 b
[18.29.30]172.20.55.101 440 c
[18.29.30]172.20.55.17 452 d
[18.29.30]172.20.55.31 414 e
[18.29.30]172.20.55.20 449 f
[18.29.30]172.20.55.8 456 g
[18.29.30]172.20.55.28 381 h
字母代表解码后的消息。第一次接收到这些消息时,它们是正确的,但是此后,消息就混乱了。
有任何想法吗?我不确定该朝哪个方向走。是线程问题,还是我必须在以后解码接收到的包?
呼啦一阵风
相关分类