Python Socket async sends and receives design

I am writing a python socket client which

  • Send message one (e.g. Hello) every 5 seconds and message two (e.g. 15 seconds) every 15 seconds
  • Receive a message anytime

I want to send and receive in different threads. However, it is still blocking. Does anyone have a suggestion?

Theme number 1

 threading.Thread(target=Thread2, args=(sock)).start() sock.recv(1024) 

Theme number 2

 def Thread2(sock): count = 0 while True: sleep(5) count = count + 5 sock.send('Hello') if count % 15 == 0 sock.send('15 seconds') 
+4
source share
1 answer

It does not block. It's just that your main thread does nothing after the first sock.recv(1024) . You must tell him to constantly collect data:

MAIN THREAD

 threading.Thread(target=Thread2, args=(sock,)).start() while True: data = sock.recv(1024) if not data: break print data 

Please note that you cannot easily interrupt this process. To do this, you need to set the thread as a daemon:

MAIN THREAD

 t = threading.Thread(target=Thread2, args=(sock,)) t.daemon = True t.start() while True: data = sock.recv(1024) if not data: break print data 

Also, when you go through args , don't forget to pass the tuple, i.e. args=(sock,) instead of args=(sock) . For Python, args=(sock) equivalent to args=sock . This is probably a criminal!

I do not see any more problems in your code.

+3
source

Source: https://habr.com/ru/post/1469171/


All Articles