#! /usr/bin/env python
#coding=utf-8
from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic
from gcutils.db import MySQLMgr
import sys
from twisted.internet.protocol import ServerFactory
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from twisted.internet import reactor
class CmdProtocol(LineReceiver):
delimiter = '\n'
def connectionMade(self):
self.client_ip = self.transport.getPeer().host
log.msg("Client connection from %s" % self.client_ip)
if len(self.factory.clients) >= self.factory.clients_max:
log.msg("Too many connections. bye !")
self.client_ip = None
self.transport.loseConnection()
else:
self.factory.clients.append(self.client_ip)
def connectionLost(self, reason):
log.msg('Lost client connection. Reason: %s' % reason)
if self.client_ip:
self.factory.clients.remove(self.client_ip)
def lineReceived(self, line):
log.msg('Cmd received from %s : %s' % (self.client_ip, line))
class MyFactory(ServerFactory):
protocol=CmdProtocol
def __init__(self, clients_max=10):
self.clients_max = clients_max
self.clients = []
log.startLogging(sys.stdout)
reactor.listenTCP(9999, MyFactory(2))
reactor.run()
在上面的代码中我们创建了"ServerFactory"类,这个工厂类负责返回“CmdProtocol”的实例。
每一个连接都由实例化的“CmdProtocol”实例来做处理。 Twisted的reactor会在TCP连接上
后自动创建CmdProtocol的实例。如你所见,protocol类的方法都对应着一种事件处理。
当client连上server之后会触发“connectionMade"方法,在这个方法中你可以做一些
鉴权之类的操作,也可以限制客户端的连接总数。每一个protocol的实例都有一个工厂
的引用,使用self.factory可以访问所在的工厂实例。
上面实现的”CmdProtocol“是twisted.protocols.basic.LineReceiver的子类,
LineReceiver类会将客户端发送的数据按照换行符分隔,每到一个换行符都会触发
lineReceived方法。稍后我们可以增强LineReceived来解析命令。
Twisted实现了自己的日志系统,这里我们配置将日志输出到stdout
当执行reactor.listenTCP时我们将工厂绑定到了9999端口开始监听。
转载于:https://my.oschina.net/u/1458120/blog/552877