This gist is deprecated and will not be edited in the future. Consider visit ninedraft/python-udp repo. It will not be deleted, however.
Works for python 3.7 and 2.7 for Mac OS and Linux(kernel>=3.9) hosts. If you'ra using linux(kernel<3.9), then use socket.O_REUSEADDR
instead of socket.SO_REUSEPORT
to share (host, port)
between multiple clients and servers.
Tricks and traps:
- Socket portability issues: How do SO_REUSEADDR and SO_REUSEPORT differ?;
- Awesome "Socket Programming HOWTO";
I just came across this gist while searching for a quick snippet to copy/paste (thanks). I won't say that the following is required, though it would be unusual not to include it.
In both the client and server, the following line should be included right before each SO_BROADCAST line (that precise order is not critical, but a good place to do it):
This makes it possible to run multiple clients and servers on a single host, on the same port. With broadcast messages that aren't just simple strings as in this example, all of those clients/servers will play nicely with each other even on the one port as long as the protocols (messages) can be distinguished from each other by content.
For example, without this change, attempting to run two copies of either the client or the server with the code at top will result in something like this:
Whereas with the change there will be two "message sent!" lines printed each second (one for each server).