Monday, September 17, 2007

Using UDP in XNA

I've had an anonymous comment left on a UdpClient post asking if I have used the UdpClient in an XNA game. Well, no I haven't--and to be honest I've not used the class much in anything else either. In fact that previous blog entry was posted after pairing with Nick on a bespoke application for a customer of ours.

But, the question got me thinking about it anyway. The comment says that they have a piece of code using the UdpClient that works in a normal .Net application, but when included in an XNA game, it no longer receives anything.

Now, I can't see why this would be the case if you are compiling to a Windows game. A Windows game is just running on the standard .Net framework, so everything should be OK. However, XBOX 360 games will run on a variation of the .Net Compact Framework, so there is a difference there to be aware of.

So assuming you're making a Windows game, why should the UdpClient now not work? Well to start I made a normal console application with the code snippet posted in the comment, and tried to get that to work. I made a separate console application to use as the sender.

And that's when the problem struck--one which I should have seen at first glance anyway. If you try to have multiple applications on the same computer accessing the same port using UdpClient you will get an exception that says "Only one usage of each socket address (protocol/network address/port) is normally permitted". (Read this article for a bit more information).

The only way we've found to stop this happening is to not use UdpClient at all, but to create Sockets yourself and use those instead.

However, I thought there must be an easier way--someone must have solved this problem before. And it looks like someone has.

I've not had a look at it in much depth, but if you want to send and receive UDP packets in XNA then take a look at the lidgren-library-network, which is on Google Code.

I don't know whether this uses UdpClient under the hood or not, but it has an XNA extension for sending Vectors and Matrices so it must have been used in some XNA games somewhere along the line.

Check it out and see if it helps.

1 comment:

willthiswork89 said...

i have recently wrote an article on this very thing, it uses Lidgrens c# built networking library. you can view this at