4

I am writing a python socket client which

  1. Send out message one (e.g. Hello) every 5 seconds and message two (e.g. 15 seconds) every 15 seconds
  2. Receive message at any time

I mean to do the send and receive in different thread. However it is still blocking. Does anyone has suggestion?

Thread #1

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

Thread #2

def Thread2(sock):
    count = 0
    while True:
        sleep(5)
        count = count + 5
        sock.send('Hello')
        if count % 15 == 0
            sock.send('15 seconds')
3
  • If you want an answer, please post the relevant part of the code that you have written. Or you'll risk to get the question closed Commented Mar 14, 2013 at 8:57
  • @Winston Not enough code. How do you create these threads? Commented Mar 14, 2013 at 9:20
  • I added the socket code Commented Mar 14, 2013 at 11:08

1 Answer 1

3

It is not blocking. It's just that your main thread does nothing after first sock.recv(1024). You have to tell it to constantly gather the data:

MAIN THREAD

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

Note that you won't be able to interrupt that process easily. In order to do that you need to set thread as 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 are passing args remember to pass a tuple, i.e. args=(sock,) instead of args=(sock). For Python args=(sock) is equivalent to args=sock. This is probably the culprit!

I can't see more issues in your code.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your answer. I just know that the python offers a module called asyncore/asynchat. Can I use that to achieve non-blocking I/O?
@Winston Sorry for this late response (somehow I've missed the question). Yep, you can use it for non-blocking I/O (I've been using asyncore a bit in my work).
Is this implementation thread-safe?
@ReeshabhRanjan no, it won't be. As long as there are only two threads, one only reading and one only writing there will be no issue.
I see, thank you. Also nice to see people addressing comments on their answers after so many years. I wish you good luck in life. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.