我正在尝试学习如何将 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?)