如何在Twisted中管理连接和客户端?

时间:2013-12-31 07:57:30

标签: python twisted

我开始使用Twisted Framework,我写了一个TCP服务器并连接到它抛出Telnet,它工作正常。现在我想使用像PyUI或GTK这样的GUI来管理连接和连接的客户端(发送数据,切断连接等)。

这是我的代码

import sys
import os
from twisted.internet import reactor, protocol
from twisted.python import log

    class Server(protocol.Protocol):

        def dataReceived(self, data):
            log.msg ("data received: %s"%data)
            self.transport.write("you sent: %s"%data)

        def connectionMade(self):
            self.client_host = self.transport.getPeer().host
            self.client_port = self.transport.getPeer().port
            if len(self.factory.clients) >= self.factory.clients_max:
                log.msg("Too many connections !!")
                self.transport.write("Too many connections, sorry\n")
                self.transport.loseConnection()
            else:
                self.factory.clients.append((self.client_host,self.client_port))
                log.msg("connection from %s:%s\n"%(self.client_host,str(self.client_port)))
                self.transport.write(
                        "Welcome %s:%s\n" %(self.client_host,str(self.client_port)))


        def connectionLost(self, reason):
            log.msg('Connection lost from %s:%s. Reason: %s\n' % (self.client_host,str(self.client_port),reason.getErrorMessage()))
            if (self.client_host,self.client_port) in self.factory.clients:
                self.factory.clients.remove((self.client_host,self.client_port))

    class MyFactory(protocol.ServerFactory):

        protocol = Server
        def __init__(self, clients_max=10):
            self.clients_max = clients_max
            self.clients = []          


    def main():
        """This runs the protocol on port 8000"""
        log.startLogging(sys.stdout)
        reactor.listenTCP(8000,MyFactory)
        reactor.run()


    if __name__ == '__main__':
        main()

感谢。

1 个答案:

答案 0 :(得分:0)

如果要编写运行UI和网络的单个Python程序(进程),首先需要选择与UI工具包的事件循环集成的适当的Twisted reactor。请参阅here

接下来,你可以从一些简单的事情开始,比如有一个按钮按下时会向所有当前连接的客户端发送短信。

另一件事:客户将连接什么?浏览器(也)?如果是这样,您可能会考虑使用WebSocket而不是原始TCP。

相关问题