python 编程之twisted详解及简单实例

yipeiwu_com5年前Python基础

python 编程之twisted详解

前言:

 我不擅长写socket代码。一是用c写起来比较麻烦,二是自己平时也没有这方面的需求。等到自己真正想了解的时候,才发现自己在这方面确实有需要改进的地方。最近由于项目的原因需要写一些Python代码,才发现在python下面开发socket是一件多么爽的事情。

    对于大多数socket来说,用户其实只要关注三个事件就可以了。这分别是创建、删除、和收发数据。python中的twisted库正好可以帮助我们完成这么一个目标,实用起来也不麻烦。下面的代码来自twistedmatrix网站,我觉得挺不错的,贴在这里和大家分享一下。如果需要测试的话,直接telnet localhost 8123就可以了。如果需要在twisted中处理信号,可以先注册signal函数,在signal函数中调用reactor.stop(),后面twisted继续call stop_factory,这样就可以继续完成剩下的清理工作了。

from twisted.internet.protocol import Factory 
from twisted.protocols.basic import LineReceiver 
from twisted.internet import reactor 
 
class Chat(LineReceiver): 
 
  def __init__(self, users): 
    self.users = users 
    self.name = None 
    self.state = "GETNAME" 
 
  def connectionMade(self): 
    self.sendLine("What's your name?") 
 
  def connectionLost(self, reason): 
    if self.name in self.users: 
      del self.users[self.name] 
 
  def lineReceived(self, line): 
    if self.state == "GETNAME": 
      self.handle_GETNAME(line) 
    else: 
      self.handle_CHAT(line) 
 
  def handle_GETNAME(self, name): 
    if name in self.users: 
      self.sendLine("Name taken, please choose another.") 
      return 
    self.sendLine("Welcome, %s!" % (name,)) 
    self.name = name 
    self.users[name] = self 
    self.state = "CHAT" 
 
  def handle_CHAT(self, message): 
    message = "<%s> %s" % (self.name, message) 
    for name, protocol in self.users.iteritems(): 
      if protocol != self: 
        protocol.sendLine(message) 
 
 
class ChatFactory(Factory): 
 
  def __init__(self): 
    self.users = {} # maps user names to Chat instances 
 
  def buildProtocol(self, addr): 
    return Chat(self.users) 
 
  def startFactory(self): 
    print 'start' 
 
  def stopFactory(self): 
    print 'stop' 
 
reactor.listenTCP(8123, ChatFactory()) 
reactor.run() 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

PYQT5设置textEdit自动滚屏的方法

在修改后的文字后面加上: self.textEdit_6.moveCursor(QTextCursor.End) 例子: self.textEdit_6.setPlainTe...

python使用scrapy发送post请求的坑

使用requests发送post请求 先来看看使用requests来发送post请求是多少好用,发送请求 Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的...

Django中提供的6种缓存方式详解

前言 由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者m...

Python中encode()方法的使用简介

 encode() 方法返回字符串的编码版本。默认编码是当前的默认字符串编码。可给予设置不同的错误处理机制。 语法 以下是encode()方法的语法: str.encode...

Python heapq使用详解及实例代码

 Python heapq 详解 Python有一个内置的模块,heapq标准的封装了最小堆的算法实现。下面看两个不错的应用。 小顶堆(求TopK大) 话说需求是这样的: 定长...