python 套接字,同时处理多个连接的最佳方法是什么?
在 python 中同时处理大量连接的最佳方法是什么?我想到的第一种方法是线程化,它可以工作,但每个线程需要 10MB RAM,这是相当昂贵的。
那么还有什么其他方法可以同时处理大量连接呢?
我在不使用线程的情况下看到的唯一问题是使用 socket.recv() 等待来自该协议客户端的数据,因此一个线程处理多个客户端将无法工作。
但这就是我问这个问题的原因,处理多个连接的最佳方法是什么?
谢谢你!
What's the best way to handle lots of connections at once in python? The first way I think of is threading, which works but at 10MB of RAM per thread that's rather expensive.
So what other ways are there to handle lots of connections at once ?
The only problem I see without using threads is that using the socket.recv() waits for data from that protocolar client so one thread handling several clients wouldn't work.
But that's why I'm asking this question, whats the best way to handle several connections?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实有大量并发连接,那么线程的一个很好的替代方案是带有回调的异步/基于事件的方法。
Python 已经为此目的提供了一个非常成熟且强大的库/框架 - Twisted。还有一个使用标准库 asyncore 模块的更简单的解决方案。从它的文档:
一般来说,异步套接字服务器最近是一个非常热门的话题(node.js 的炒作就是见证),我相信你可以在网上找到很多有趣的材料。
A good alternative to threads, if you have a truly large amount of simultaneous connections, is an asychronous/events based approach with callbacks.
Python already has a very mature and powerful library/framework for this purpose - Twisted. There's also a simpler solution using the standard library
asyncore
module. From its docs:Generally, asynchronous socket servers is a very hot topic lately (node.js hype as a witness), I'm sure you can find a lot of interesting material online.