twisted 网络通讯的简单例子

#! /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端口开始监听。
相关文章
相关标签/搜索