简体   繁体   English

在Python中处理来自多个套接字的传入数据

[英]Handling Incoming Data from Multiple Sockets in Python

Background: I have a current implementation that receives data from about 120 different socket connections in python. 背景:我有一个当前的实现,该实现从python中约120个不同的套接字连接接收数据。 In my current implementation, I handle each of these separate socket connections with a dedicated thread for each. 在当前的实现中,我使用专用线程处理每个单独的套接字连接。 Each of these threads parse the data and eventually store it within a shared locked dictionary. 这些线程中的每个线程都会解析数据,并最终将其存储在共享的锁定字典中。 These sockets DO NOT have uniform data rates, some sockets get more data than others. 这些套接字没有统一的数据速率,某些套接字比其他套接字获得更多的数据。

Question: Is this the best way to handle incoming data in python, or does python have a better way on handling multiple sockets per thread? 问题:这是处理python中传入数据的最佳方法,还是python在处理每个线程多个套接字方面有更好的方法?

Using an asynchronous approach will make you much happier. 使用异步方法将使您更加快乐。 For an example of a well-done implementation of this as a well-known application Tornado is perfect. 作为一个众所周知的应用程序,它的一个很好的实现示例就是龙卷风 You can easily use Tornado's ioloop for things other than web servers, too. 您也可以轻松地将Tornado的ioloop用于Web服务器以外的其他设备。

There are alternative libraries such as gevent ; 还有其他库,例如gevent but I believe Tornado is a better place to look at first since it both provides the loop and a web server implemented on top of it as a great example of how to use the loop well. 但是我认为Tornado首先是一个更好的地方,因为它既提供了循环又在其上实现了Web服务器,这是如何很好地使用循环的一个很好的例子。

If you're using threads, that's basically the way you'd go about it. 如果您使用线程,那基本上就是您要使用的线程。

The alternative is to use one of the various asynchronous networking libraries out there, such as Twisted , Tornado , or GEvent . 另一种选择是使用各种异步网络库之一,例如TwistedTornadoGEvent

As mentioned in Asynchronous UDP Socket Reading question from you, asyncoro can be used to process many asynchronous sockets efficiently. 正如您在“ 异步UDP套接字读取”问题中提到的那样, asyncoro可用于有效地处理许多异步套接字。 Another benefit with asyncoro in your problem is that you don't need to worry about locking shared dictionary, as with asyncoro at most one coroutine is executing at any time and there is no forced preemption. 在您的问题中使用asyncoro的另一个好处是,您不必担心锁定共享字典,因为使用asyncoro最多可以随时执行一个协程,并且没有强制抢占。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM