C#开始接收UDP
我正在尝试学习如何将BeginReceive用于UDP,以下是我的经验:C#开始接收UDP,c#,.net,udp,udpclient,C#,.net,Udp,Udpclient,我正在尝试学习如何将BeginReceive用于UDP,以下是我的经验: Console.WriteLine("Initializing SNMP Listener on Port:" + port + "..."); UdpClient client = new UdpClient(port); //UdpState state = new UdpState(client, remoteSender); try
Console.WriteLine("Initializing SNMP Listener on Port:" + port + "...");
UdpClient client = new UdpClient(port);
//UdpState state = new UdpState(client, remoteSender);
try
{
client.BeginReceive(new AsyncCallback(recv), null);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void recv(IAsyncResult res)
{
int port = 162;
UdpClient client = new UdpClient(port);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
Console.WriteLine(Encoding.UTF8.GetString(received));
client.BeginReceive(new AsyncCallback(recv), null);
}
什么也没发生,代码只是结束了,甚至没有调用recv方法。为什么呢
编辑:
增加:-
Console.ReadLine();
现在它在下面一行给了我一个例外:
Only one usage of each socket address is normally permitted.
已尝试:-
try
{
client.BeginReceive(new AsyncCallback(recv), client);
}
private static void recv(IAsyncResult res)
{
// int port = 162;
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);
byte[] received = res.AsyncState.EndReceive(res, ref RemoteIpEndPoint);
Console.WriteLine(Encoding.UTF8.GetString(received));
res.AsyncState.BeginReceive(new AsyncCallback(recv), null);
}
catch (Exception e)
{
Console.WriteLine(e);
}
错误:
'object' does not contain a definition for 'EndReceive' and no extension method 'EndReceive' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
如果代码的第一部分本质上是主函数的主体,那么它的结束就不应该让您感到惊讶。放
Console.Readline();
在关闭}
的main
之前等待
当一些数据到达时,recv
将被异步调用。然后,您需要从正在等待的UDP客户端读取接收到的数据。要访问此客户端,您需要通过状态参数BeginReceive
client.BeginReceive(new AsyncCallback(recv), client);
最后从callbacks IAsyncResult参数中获取它
UdpClient client = (UdpClient)res.AsyncState;
将客户机存储在类字段中可能更容易(但灵活性较低)
现在您可以从
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
在发布此问题之前,您是否中断了它?看看会发生什么?看到哪里出错了吗?我这样做了,它在UdpClient client=newudpclient(port)处给了我一个异常;那么这个端口可能正在使用中。选择另一个。然而,这实际上并没有关系。我在main中打开端口,作为调用beginreceive的引用,然后在recv中再次这样做,这不是预先准备的。当然,你不能这样做。你不需要这样做。只需将
客户机
作为BeginReceive
的参数放入main(而不是null)。然后从res中提取recv
中的客户机(它处于异步状态)。我尝试了,请参见上面的编辑,它给了我正在传递的对象参数一个错误