Tuesday, May 22, 2007

Set LocalEndPoint in UdpClient

I haven't done that much work using UDP as a protocol, most of the time I'm lucky enough to use TCP. Now some work has called for UDP to be used, and we're currently just figuring out how to use it.

Each UDP packet will have a source and destination port, and if the receiver needs to send a response then it will send it to the source port specified in the original packet.

The default constructor for the .Net UdpClient assigns a value for this port for you, which is OK if you don't need a response, but if you want a separate process to handle the response then you need to use a different constructor to specify a port value and/or address.

Use UdpClient(Int32) to just set the local port value, or UdpClient(IPEndPoint) to set address and port values.

3 comments:

Anonymous said...

Have you used Udpclient on a xna game?
I need some help receiving data through udp in a xna game
string returnData never changes.
This code works in simple C# but does not in xna.

protected override void Initialize()
{...
HiloRecibir = new Thread(RecibirDatos2);
HiloRecibir.Start();
...
}

private void RecibirDatos2()
{
int GroupPort = 8111;
UdpClient udp = new UdpClient(GroupPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 0);
byte[] buff = new byte[1024];
buff = udp.Receive(ref groupEP);
string returnData = Encoding.ASCII.GetString(buff);
udp.Close();
}

Ian Dykes said...

Thanks for the comment.

Read my answer here

syslog said...

Why did you use: byte[] buff = new byte[1024];
instead of byte[] buff; ???