Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4999584
  • 博文数量: 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-12-08 13:08:51

一下是聊天服务端代码:(实现广播)
  1. #! /usr/bin/env python
  2. #coding=utf-8

  3. from twisted.internet import protocol
  4. from twisted.protocols import basic
  5. from twisted.python import log
  6. from twisted.internet import reactor
  7. import sys

  8. class ConfigServer(basic.LineReceiver):
  9.     def __init__(self):
  10.         pass

  11.     def lineReceived(self, line):
  12.         if line == 'quit':
  13.             self.sendLine("Goodbye.")
  14.             self.transport.loseConnection()
  15.         else:
  16.             self.broadcast(line)
  17.     
  18.     def broadcast(self, msg):
  19.         for client in self.factory.clients:
  20.             client.sendLine("someone said: %s" % msg);

  21.     def connectionMade(self):
  22.         self.factory.clients.append(self)
  23.         print "Connect from %s.." % self.transport.getHost()
  24.         self.sendLine("Welcome...%s" % self.transport.getHost())

  25.     def connectionLost(self, reason):
  26.         self.factory.clients.remove(self)
  27.         # self.sendLine("Disconnect...%s" % self.transport.getHost())
  28.         pass

  29. class ConfigServerFactory(protocol.ServerFactory):
  30.     protocol = ConfigServer
  31.     clients = []

  32. def main():
  33.     log.startLogging(sys.stdout)
  34.     reactor.listenTCP(8080,ConfigServerFactory())
  35.     reactor.run()
  36.     
  37. if __name__ == '__main__':
  38.     main()

 

阅读(1228) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~