Daniel Lindberg wrote:
Hi, im a beginner in C# and i just cant seem to get my udp broadcasting to
work. What happens is that it just locks down on the Receive call and
never gets any data.
I have the code for the server who answers the broadcast, so i know that
it sends a reply, but i cant figure out why my C# client cant receive it..
Any input on whats wrong with my code will be appreciated
//My code...
byte[] buffer = new byte[50];
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 0));
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 4242));
socket.Send(System.Text.ASCIIEncoding.ASCII.GetByt es((char)2+"0"+(char
9+"1"
+(char)3));
socket.Receive(buffer, 0, 50, SocketFlags.None);
textBox1.Text = Encoding.ASCII.GetString(buffer);
Hi Daniel,
For UDP Broadcasting, you should be using the SendTo and ReceiveFrom
methods. You also shouldn't be connecting to anything.
The ReceiveFrom method takes an IPEndPoint as a ref parameter, which should
be initialised as:
EndPoint remoteEndPoint = new IPEndPoint( IPAddress.Broadcast, 4242 );
Then, call socket.ReceiveFrom using 'ref remoteEndPoint' as the parameter.
The remoteEndPoint object will also be modified to point to the endpoint
that the broadcast message originated from.
Here's a short example:
///
public void BroadcastTest ( )
{
// Instantiate
Socket sck = new Socket( AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp );
// Bind
sck.Bind( new IPEndPoint( IPAddress.Any, 0 ) );
// Broadcast ABCD
sck.SendTo( new byte[] { 0x41, 0x42, 0x43, 0x44 },
new IPEndPoint( IPAddress.Broadcast, 4242 ) );
// Receive on the broadcast IP, port 4242
EndPoint remoteEndPoint = new IPEndPoint( IPAddress.Broadcast, 4242 );
byte[] recvBuffer = new byte[128];
int bytesReceived = sck.ReceiveFrom( recvBuffer, ref remoteEndPoint );
}
///
Note: I typed this straight into KNode, I haven't tested it in the
slightest... but it just so happens that I've been coding some UDP
broadcast stuff lately, so this is fresh in my memory.
--
Hope this helps,
Tom Spink