pythonsocket如何實現一個服務器對多個客戶端進行交互?
用twisted,用工廠管理連接,每個連接建立transport. 使用簡單方便!參看下面代碼:
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Example socket server using Twisted.
@see: U{Documentation for this example<http://pyamf.org/tutorials/actionscript/socket.html>}
@since: 0.1
"""
try:
import twisted
except ImportError:
print "This examples requires the Twisted framework. Download it from http://twistedmatrix.com"
raise SystemExit
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from datetime import datetime
import pyamf
class TimerProtocol(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
def connectionLost(self, reason):
Protocol.connectionLost(self, reason)
print "locst connection:",reason
#客戶端沒斷開一個鏈接,總連接數-1
self.factory.number_of_connections -= 1
print "number_of_connections:",self.factory.number_of_connections
def connectionMade(self):
#如果服務器連接數超過最大連接數,拒絕新鏈接建立
if self.factory.number_of_connections >= self.factory.max_connections:
self.transport.write('Too many connections, try again later')
self.transport.loseConnection()
return
#總連接數+1
self.factory.number_of_connections += 1
self.timeout_deferred = reactor.callLater(TimerProtocol.timeout, self.transport.loseConnection)
def dataReceived(self, data):
#去除server收到client數據兩端的空格
data = data.strip()
#如果收到的是'start'命令
if data == 'start':
# start sending a date object that contains the current time
if not self.started:
self.start()
elif data == 'stop':