UdpClient.() 与 UdpClient(端口)

发布于 2024-12-04 19:44:54 字数 947 浏览 0 评论 0原文

我有一个小问题和一个解决方案,但我想了解到底发生了什么。 根据 UdpClient 的构造函数,我使用 EndReceive() 是否抛出套接字异常(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);
    }

I have a little problem and a Solution, but i would like to understand whats happening exactly.
Depending on the constructor of UdpClient I use EndReceive() throws a Socket Exeption or not( 10054 - An existing connection got closed by the remote host (translated from german))

thanks for any hint!
Vincent

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);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世俗缘 2024-12-11 19:44:54

情况 1:udpClient = new UdpClient() - 将套接字绑定到随机本地端口
情况 2:udpClient = new UdpClient(8000) - 您将套接字绑定到本地端口 8000

也许在情况 1 远程主机尝试发送到随机端口并被防火墙拒绝?

case 1: udpClient = new UdpClient() - you binding socket to random local port
case 2: udpClient = new UdpClient(8000) - you binding socket to local port 8000

Maybe in case 1 remote host try send to random port and rejected by firewall?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文