Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sockets stop recv from hanging?

I am trying to create a two player game in pygame using sockets, the thing is, when I try to receive data on on this line:

message = self.conn.recv(1024)

python hangs until it gets some data. The problem with this is that is pauses the game loop when the client is not sending anything through the socket and causes a black screen. How can I stop recv from doing this?

Thanks in advance

like image 767
Slidon Avatar asked Nov 29 '13 16:11

Slidon


2 Answers

you can use signal module to stop an hangs recv thread.

in recv thread:

try:
    data = sock.recv(1024)
except KeyboardInterrupt:
    pass

in interpret thread:

signal.pthread_kill(your_recving_thread.ident, signal.SIGINT)
like image 101
yangtao Avatar answered Sep 20 '22 05:09

yangtao


Use nonblocking mode. (See socket.setblocking.)

Or check if there is data available before call recv. For example, using select.select:

r, _, _ = select.select([self.conn], [], [])
if r:
    # ready to receive
    message = self.conn.recv(1024)
like image 23
falsetru Avatar answered Sep 18 '22 05:09

falsetru