欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

pythonsocket如何實現一個服務器對多個客戶端進行交互?

傅智翔2年前14瀏覽0評論

用twisted,用工廠管理連接,每個連接建立transport.使用簡單方便!參看下面代碼:

#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服務器: