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端口開始監聽。
相關文章
相關標籤/搜索