python套接字阻止recv挂起? [英] python sockets stop recv from hanging?

查看:128
本文介绍了python套接字阻止recv挂起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用套接字在 pygame 中创建一个两人游戏,问题是,当我尝试在这条线上接收数据时:

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 挂起,直到它获得一些数据.问题在于,当客户端未通过套接字发送任何内容并导致黑屏时,会暂停游戏循环.我怎样才能阻止 recv 这样做?

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?

提前致谢

推荐答案

使用非阻塞模式.(参见 socket.setblocking.)

Use nonblocking mode. (See socket.setblocking.)

或者在调用recv之前检查是否有可用的数据.例如,使用 select.select:

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)

这篇关于python套接字阻止recv挂起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆