脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 编程之twisted详解及简单实例

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

2020-09-19 14:55Python教程网 Python

这篇文章主要介绍了python 编程之twisted详解及简单实例的相关资料,需要的朋友可以参考下

python 编程之twisted详解

前言:

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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()

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

原文链接:http://blog.csdn.net/feixiaoxing/article/details/50499961

延伸 · 阅读

精彩推荐