我正在努力学习如何将BeginReceive用于UDP,下面是我所拥有的:
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?)发布于 2013-07-11 08:09:13
如果代码的第一部分本质上是您的主要函数的主体,那么您不应该对它的结束感到惊讶。放一个
Console.Readline();在关闭} of main之前等待。
一旦一些数据到达,recv将被异步调用。然后,您需要从等待的UDP客户端读取接收的数据。为了访问这个客户机,您将通过BeginReceive的状态参数传递它
client.BeginReceive(new AsyncCallback(recv), client);并最终从回调IAsyncResult参数获得它。
UdpClient client = (UdpClient)res.AsyncState;在类字段中存储客户机可能更容易(但不那么灵活)。
现在您可以从
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);https://stackoverflow.com/questions/17588099
复制相似问题