我回答了一个听起来与您的问题惊人相似的问题,其中有人有一个家庭作业来创建一个客户机-服务器设置,每个连接都在一个新线程中处理:https://stackoverflow.com/a/9522339/496445
总的来说,您有一个主服务器循环,不断地寻找一个新的连接进来。当它出现时,您将它交给一个线程,该线程将对新的通信进行自己的监视。
关于异步与线程的额外信息There are only two ways to have a program on a single processor do
“more than one thing at a time.” Multi-threaded programming is the
simplest and most popular way to do it, but there is another very
different technique, that lets you have nearly all the advantages of
multi-threading, without actually using multiple threads. It’s really
only practical if your program is largely I/O bound. If your program
is processor bound, then pre-emptive scheduled threads are probably
what you really need. Network servers are rarely processor bound,
however.
正如这句话所说,使用asyncore和threading在很大程度上应该是互斥的选项。上面的链接是线程方法的一个示例,其中服务器循环(在单独的线程或主线程中)执行阻塞调用以接受新的客户端。当它得到一个线程时,它生成一个线程,然后继续处理通信,服务器再次进入阻塞调用。
在使用asyncore的模式中,您将使用它的async循环,该循环将依次为发生的各种活动调用您自己注册的回调。这里没有线程,而是对活动的所有打开文件句柄进行轮询。你有一种同时做事的感觉,但在幕后,它是按顺序安排每件事。