UDP is a useful protocol to use to communicate between remote systems connected over TCP/IP. Python can communicate over UDP via its sockets library. I’ve had to develop UDP code from scratch several times now because I change jobs, lose the files, etc. Thus, I’m going to post a simple UDP example in Python with fully commented code so I can refer back to it later.
This application does both UDP transmit and receive and as a bonus it uses threads to do so. The main thread sets up the receive thread and then does the transmit. The receive thread will receive then echo back whatever it gets and the transmit thread will print whatever it gets.
It’s worth noting that using UDP or TCP to communicate between threads is a pretty legitimate communication method (from what I’m told). Or maybe it was between processes? Either way, this code works and should serve as a good example of simple UDP communication in both directions.
Python Code
Example Output
UDP Tx/Rx Example application
Press Ctrl+C to exit
RX: Receiving data on UDP port 8000
Transmitting to 127.0.0.1 port 8000
Type anything and press Enter to transmit
TX: test
RX: test
TX: testing
RX: testing
TX: hello world
RX: hello world
TX: Received Ctrl+C… initiating exit
Blocking Sockets
Often in multi-threaded programming you’ll want a blocking socket so that you can let other tasks run until there’s data available for you to play with. You can modify the RX thread to do so: