#Copyright(c)ThePyAMFProject.
#SeeLICENSE.txtfordetails.
“””
ExamplesocketserverusingTwisted.
@see:U{Documentationforthisexample<http://pyamf.org/tutorials/actionscript/socket.html>}
@since:0.1
“””
try:
importtwisted
exceptImportError:
print”ThisexamplesrequirestheTwistedframework.Downloaditfromhttp://twistedmatrix.com”
raiseSystemExit
fromtwisted.internet.protocolimportProtocol,Factory
fromtwisted.internetimportreactor
fromdatetimeimportdatetime
importpyamf
classTimerProtocol(Protocol):
interval=1.0#客户端链接到server后,server往客户端发送时间的间隔
encoding=pyamf.AMF3
timeout=20#客户端链接到server后多少时间不操作就断开链接的timeout
def__init__(self):
self.started=False
#设置编码器
self.encoder=pyamf.get_encoder(self.encoding)、
#设置server端将数据编码成amf后存放的缓存地址
self.stream=self.encoder.stream
defconnectionLost(self,reason):
Protocol.connectionLost(self,reason)
print”locstconnection:”,reason
#客户端没断开一个链接,总连接数-1
self.factory.number_of_connections-=1
print”number_of_connections:”,self.factory.number_of_connections
defconnectionMade(self):
#如果服务器连接数超过最大连接数,拒绝新链接建立
ifself.factory.number_of_connections>=self.factory.max_connections:
self.transport.write(‘Toomanyconnections,tryagainlater’)
self.transport.loseConnection()
return
#总连接数+1
self.factory.number_of_connections+=1
self.timeout_deferred=reactor.callLater(TimerProtocol.timeout,self.transport.loseConnection)
defdataReceived(self,data):
#去除server收到client数据两端的空格
data=data.strip()
#如果收到的是’start’命令
ifdata==’start’:
#startsendingadateobjectthatcontainsthecurrenttime
ifnotself.started:
self.start()
elifdata==’stop’:
使用多线程,下面的代码,简单实现一个多线程的web服务器: