用twisted实现一个聊天应用,两个客户端可以通过一个twisted进行聊天交互

windows环境装了twisted后 还要装个软件 zope.interface-4.0.5.win32-py2.7.exe

http://twistedmatrix.com/trac/wiki/Downloads

image

twised_client.py:

import sys
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class EchoClient(LineReceiver):
    end = "exit"
    def connectionMade(self):
        self.sendLine("start:")

    def lineReceived(self, line):
        print line
        print 'send: ',
        msg = sys.stdin.readline()
        self.sendLine(msg)       
        if line == self.end:
            self.transport.loseConnection() 
class EchoClientFactory(ClientFactory):
    def startedConnecting(self, connector):
        print "connection starting..."
    def buildProtocol(self, addr):
        print addr
        return EchoClient()
    def clinetConnectionLost(self, connector, reason):
        print "lose reason: ", reason
    def clientConnectionFailed(self, connector, reason):
        print "faild reason: ", reason

reactor.connectTCP('127.0.0.1', 8888, EchoClientFactory())
reactor.run()

twisted_server.py:

from twisted.protocols import basic
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol

connected = []

class Echo(Protocol):
    def connectionMade(self):
        self.transport.write("hi, welcome!\n")
        connected.append(self)
    def dataReceived(self, data):
        for msg in connected:
            if msg != self:
                msg.transport.write("receive: %s" %data,)

    def connectionLost(self, reason):
        print "Lost a client!"
        connected.remove(self)
factory = Factory()
factory.protocol = Echo
reactor.listenTCP(8888, factory)
reactor.run()

 

开一个服务端 和2个客户端:

image

 

一个基于事件驱动,异步的python高性能(?)网络开发框架

三个模型对比:

 

image image image

(异步模型处理起来比较方便)

您可以选择一种方式赞助本站