我有一个问题和解决方案,但我想了解到底发生了什么。 根据UdpClient的构造函数,我使用EndReceive()抛出Socket Exeption与否(10054 - 远程主机关闭现有连接(从德语翻译))
感谢任何提示! 文森特
private UdpClient udpClient;
void recv(IAsyncResult res)
{
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udpClient.EndReceive(res, ref remote); // code stops here in debug
// do something with data received from remote
udpClient.BeginReceive(new AsyncCallback(recv), null);
}
private void Form1_Load(object sender, EventArgs e)
{
//udpClient = new UdpClient(); // will throw exception
udpClient = new UdpClient(8000); // will not throw exception
udpClient.Connect("127.0.0.1", 8000);
udpClient.BeginReceive(new AsyncCallback(recv), null);
}
private void button1_Click(object sender, EventArgs e)
{
udpClient.Send(Encoding.ASCII.GetBytes("Hallo"), 5);
}
答案 0 :(得分:1)
案例1:udpClient = new UdpClient() - 将套接字绑定到随机本地端口
案例2:udpClient = new UdpClient(8000) - 将套接字绑定到本地端口8000
也许以防万一1远程主机尝试发送到随机端口并被防火墙拒绝?