tags:

views:

146

answers:

1

Here is my code

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

I use above code to try find a server. First I broadcast a message and then I wait for a response from the server.

A test I made with the server written in C++ and running in Windows Vista, client written in C# and run on the same machine with server.

Problem is: The server can receive message which client broadcast, but client can not receive anything from server.

I try to write a client with C++ and it work like a charm, I think my problem is in C# client.

+1  A: 

I would start listening on that port before you broadcast. You're using UDP which is connectionless so you could be missing your packet.

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