udp无法接收任何数据

时间:2010-04-17 02:53:11

标签: c# c++ sockets udp

这是我的代码

Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));

// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);

//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);
sck2.ReceiveFrom(buffer, ref remoteEndPoint); //<<< I never pass this line

我使用上面的代码来尝试查找服务器。首先,我播放一条消息,然后等待服务器的响应。

我使用C ++编写并在Windows Vista中运行的服务器进行的测试,使用C#编写的客户端与服务器在同一台机器上运行。

问题是:服务器可以接收客户端广播的消息,但客户端无法从服务器接收任何内容。

我尝试使用C ++编写一个客户端,它就像一个魅力,我认为我的问题是在C#客户端。

1 个答案:

答案 0 :(得分:2)

在广播之前,我会开始收听该端口。您正在使用无连接的UDP,因此您可能错过了数据包。

Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.Bind(new IPEndPoint(IPAddress.Any, 0));
//Wait response from server
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck2.Bind(new IPEndPoint(IPAddress.Any, udp_listen_port));
byte[] buffer = new byte[128];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, udp_listen_port);

// Broadcast to find server
string msg = "Imlookingforaserver:" + udp_listen_port;
byte[] sendBytes4 = Encoding.ASCII.GetBytes(msg);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"), server_port);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sck.SendTo(sendBytes4, groupEP);


sck2.ReceiveFrom(buffer, ref remoteEndPoint);