UdpClient.Receive(...)不接收任何数据

时间:2013-05-28 19:47:24

标签: c# sockets udp

我有一个套接字服务器(用C ++编写),它接收来自客户端的请求并发回响应。所以,我的测试客户端应用程序(C#)非常简单:

        try {
            UdpClient udpClient = new UdpClient(10241);

            // Connect
            udpClient.Connect(server_ip_address,  10240);

            // prepare the packet to send
            iWritableBuff wbuff = new iWritableBuff();
            [ ... ]

            // Send 
            udpClient.Send(wbuff.GetBuff(), (int)wbuff.Written());

            // Receive a response
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
            Console.WriteLine("We've got some data from the server!!! " + receiveBytes.Length + " bytes.");

            udpClient.Close();
        } catch (Exception e) {
            Console.WriteLine("ERROR: " + e.ToString());
        }

我在同一台计算机上运行这两个应用程序。服务器从客户端端口10241接收对端口10240的请求,并将响应发送回客户端端口10241,但客户端从不接收它。所以,我确信服务器会发回数据包,因为一切都与C ++客户端完美配合。这意味着我在C#客户端上做错了。有什么想法吗?

谢谢!

P.S.>只需使用Berkley Socket C#client进行测试:

        try {
            // Create socket
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // Bind
            IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
            s.Bind(myEP);

            // prepare the packet to send
            iWritableBuff wbuff = new iWritableBuff();
            [ ... ]

            // Send it
            IPEndPoint sEP = new IPEndPoint(IPAddress.Parse(server_ip_address), 10240);
            int res = s.SendTo(wbuff.GetBuff(), (int)wbuff.Written(), 0, sEP);

            // Receive the response
            byte[] receiveBytes = new Byte[1024];
            EndPoint recEP = new IPEndPoint(IPAddress.Any, 0);
            res = s.ReceiveFrom(receiveBytes, ref recEP);
            Console.WriteLine("We've got some data from the server!!! " + res + " bytes.");
        } catch (Exception e) {
            Console.WriteLine("ERROR: " + e.ToString());
        }

它完美无缺! UdpSocket出了什么问题?

1 个答案:

答案 0 :(得分:1)

不确定这是否适用于不广播数据包但只是将其发送到指定地址的UDPClients,但我遇到了类似的障碍。

我有一个UDPClient广播了一个udp数据包,用于在我们的网络上发现一些自定义机器。当我尝试接收服务器只是回显的消息时,它将不会收到信息并且会超时。事实证明,如果您使用广播消息的UDPClient,它将无法接收消息。它没有在任何地方记录,除了我很幸运地遇到msdn上的一个论坛主题。

解决方案是发送消息,立即关闭套接字,在同一端口上打开一个新的UDPClient,然后使用这个新的UDPClient接收回送的UDP数据包。很烦人。

给它一个镜头,看它是否有效。它肯定适用于发送广播数据包。

相关问题