I am trying to create a separate thread in a client that revives messages from a server socket in a non-blocking manner. Since my original code is too long and a bit of a hassle to explain in order to understand it, I have created an example program which focuses on what I want to do. I try to create two separate threads , say Thread t1 and Thread t2. Thread t1 polls the socket to check for any received data whereas Thread t2 does whatever task it is assigned to do. What I am expecting it to do is, Thread t1 always polls and if a data is received it prints it on the screen and Thread t2 executes in parallel doing whatever it is doing. But, I cannot get it working for some reason.
My example program is:
import threading
import time
import threading
from time import sleep
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 5555))
s.setblocking(0)
s.sendall(str.encode('Initial Hello'))
def this_thing():
while True:
try:
data = s.recv(4096)
print(data.decode('utf-8'))
except:
pass / break #not sure which one to use. Neither of it works
def that_thing():
for i in range(10000):
sleep(3)
s.sendall(str.encode('Hello')
print('happening2')
threading.Thread(target=this_thing(), args=[]).start()
threading.Thread(target=that_thing(), args=[]).start()
Note: The server socket is a simple server that sends a message to all connected sockets if a message was received by it.
When I run the program by breaking out in the exception in Thread t1, only my Thread t2 is keeps running. I.e Thread t1 does not receive any data sent from the server
[WinError 10035] A non-blocking socket operation could not be completed immediatelyWhich makes sense, but if i change the socket to blocking it never really gets out ofThread t1until I receive a message which is not what I want to do. Any way around this?