Python 游戏服务器中的 TCP 套接字
我计划制作一个 Python 游戏服务器,但我不知道如何设置它。
我遇到的问题是我需要服务器侦听连接(使用 socket.socket.accept()
?),但它会挂起代码直到建立连接,这意味着服务器无法在等待期间做任何其他事情。
多线程可以解决这个问题吗?
另一个问题是每个客户端是否应该在游戏开始时连接并在游戏持续时间内保持连接,或者是否应该每秒建立连接以发送/接收数据。
I plan to make a Python game server but I can't see how to set it up.
The problem I have is that I need the server to listen for connections (with socket.socket.accept()
?) but it hangs the code until a connection is made, which means the server can't do anything else while it is waiting.
Is multi-threading the solution to this?
The other question is whether each client should connect at the start of the game and stay connected for the duration, or if the connection should be made every second to send/receive data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确,
socket.accept()
是按设计阻塞的。要在后台处理连接,请参阅SocketServer.ThreadingMixIn
示例。http://docs.python.org/library/socketserver.html#asynchronous-mixins
Correct,
socket.accept()
blocks by design. To handle connection in the background seeSocketServer.ThreadingMixIn
for example.http://docs.python.org/library/socketserver.html#asynchronous-mixins