Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4995506
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2011-10-02 11:14:52

如果你之前没有安装Twisted模块,则先安装(包括安装zope.interface模块):
下载最新版本的tar包,然后安装
安装方法很简单,都是:
1. 解压缩
2. python setup.py build
3. python setup.py install
  1. [root@lvdbing python]# cat twistedchatserver.py
  2. #!/usr/bin/env python
  3. # -*- coding:utf-8 -*-
  4. # vim: set ai cindent et sw=4 ts=4 nowrap foldmethod=marker:

  5. from twisted.internet.protocol import Factory
  6. from twisted.protocols.basic import LineOnlyReceiver
  7. from twisted.internet import reactor

  8. class Chat(LineOnlyReceiver):
  9.     def lineReceived(self, data):
  10.          self.factory.sendAll("%s: %s" % (self.getId(), data))

  11.     def getId(self):
  12.         return str(self.transport.getPeer())

  13.     def connectionMade(self):
  14.         print "New connection from", self.getId()
  15.          self.transport.write("Welcome to the chat server, %s\n" % self.getId())
  16.          self.factory.addClient(self)

  17.     def connectionLost(self, reason):
  18.          self.factory.delClient(self)

  19. class ChatFactory(Factory):
  20.      protocol = Chat

  21.     def __init__(self):
  22.          self.clients = []

  23.     def addClient(self, newclient):
  24.          self.clients.append(newclient)

  25.     def delClient(self, client):
  26.          self.clients.remove(client)

  27.     def sendAll(self, message):
  28.         for proto in self.clients:
  29.              proto.transport.write(message + "\n")

  30. reactor.listenTCP(51423, ChatFactory())
  31. reactor.run()
阅读(1429) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~