Skip to content
Advertisement

Python non-blocking socket

Hi I am trying to create a very simple peer-to-peer chatting program in python. The first user can runs the server.py program below to bind to a socket.

JavaScript

Then another user can use netcat to connect to the server and communicate. However, the program is only able to get the user’s input and send to the other side. The user from the other side is unable to send messages.

One sided communication

Advertisement

Answer

input() blocks, so you are falling through your chat function and entering the input() loop and never checking for receiving again. Receive on the thread and enter the input loop on the main thread. TCP is full duplex so you can send/recv at the same time on two threads without turning off blocking.

I also needed to add a newline to the send() as my netcat was line-buffering.

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