您的位置:首页 > 理论基础 > 计算机网络

【脚本语言系列】关于Python网络通讯Twisted网络框架,你需要知道的事

2017-06-13 14:27 721 查看
【脚本语言系列】关于Python网络通讯Twisted网络框架,你需要知道的事

如何使用Twisted框架

实现简单的服务器端

# -*- coding:utf-8 -*-
from twisted.internet import protocol, reactor, endpoints

class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)

class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()

endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory())
reactor.run()


# -*- coding:utf-8 -*-
from twisted.internet import reactor
from twisted.internet.protocal import Protocol, Factory

class SimpleServer(Protocol):
def connectionMade(self):
print "Get connection from", self.transport.client

def connectionLost(self, reason):
print self.transport.client, "disconnected"

def dataReceive(self, data):
print data

factory = Factory()
factory.protocol = SimpleServer

port = 1234
reactor.listenTCP(port, factory)
reactor.run()


什么是Twisted框架

Twisted是一个面向对象,基于事件驱动的顶级通讯框架,类似ACE(Adaptive Communication Environment,自适应网络通讯环境)网络框架。Twisted适合用来编写服务器端的应用程序。

为何使用Twisted框架

为了便于编写异步通讯的程序,可以使用Twisted框架。

区别于使用轮询的方案来处理异步通讯传输时的连接,Twisted采用的是一种事件驱动的方式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐