且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python中的多线程多客户端服务器

更新时间:2022-05-01 21:35:48

使用扭曲,它使您可以在单个线程中同时处理多个客户端,并提供更好的API.

It's much simpler and better to implement this sort of thing using Twisted, which lets you handle multiple clients concurrently in a single thread, as well as providing a nicer API.

以下是您使用Twisted编写聊天服务器的方式( chatserver.py ):

Here's how you write a chat server using Twisted (full example in chatserver.py):

class MyChat(basic.LineReceiver):
    def connectionMade(self):
        print "Got new client!"
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        print "received", repr(line)
        for c in self.factory.clients:
            c.message(line)

    def message(self, message):
        self.transport.write(message + '\n')

对于每个用户,都会创建一个MyChat对象,并且事件循环会在开始/停止事件以及从客户端接收到一行时调用其方法.在这种情况下,它只将接收到的每一行发送给系统中的所有客户端.由于它在单个线程中运行,因此不需要锁.

For each user, a MyChat object gets created, and the event loop calls its methods for start/stop events and when a line is received from the client. In this case, it just send every line it receives to all the clients in the system. Since it runs in a single thread, no locks are needed.