Skip to content
Advertisement

How to send and receive data the same time Python UDP socket

I just learned about #python recently, I have done a small project about rasberry pi. I want to transmit and receive data between Server is Laptop, client is Ras via UDP protocol, I use Python’s socket library. Transmit sensor data from ras to laptop, and transmit control commands from laptop to ras. Data from ras must always be transmitted, so I used a while true loop with time.sleep. The problem is again at this point, the control command from the laptop is not always sent, only sent when necessary, I receive the control command on Ras by recvfrom() is also in the while True loop, so when not transmitting the control command is the while true loop stuck here, so the data from the sensor cannot be transmitted anymore. m.n help me give advice or keywords for this article. Thank you.

server.py

JavaScript

cilent.py

JavaScript

Advertisement

Answer

If the sending of the data from the RasPi to the PC is a fairly independent thing that must always run, you could consider making a separate thread of execution for it so you can sleep() in there and generally do whatever you want without interfering with receiving occasional commands that you must respond to. There’s a great description of threads here but it might look like this:

JavaScript

Here’s the output from a sample run:

JavaScript

Likewise, if you don’t want to hang/block on the RasPi waiting for commands from the PC, you could start another thread that sits in a tight loop, doing blocking reads from the UDP command port. It could then put the commands into a Python Queue for the main program to read whenever it wants, and it can do the read with a timeout which means the main thread doesn’t block when there are no incoming commands. Good description here, but the code might look something like this:

JavaScript

Note: I don’t believe Python sockets are thread-safe, so you would probably want to send and receive on different ports with this approach – but that shouldn’t be a problem as there are 65,000 ports.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement