Chinaunix首页 | 论坛 | 博客
  • 博客访问: 547203
  • 博文数量: 142
  • 博客积分: 2966
  • 博客等级: 少校
  • 技术积分: 1477
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-07 22:37
文章分类

全部博文(142)

文章存档

2013年(3)

2012年(21)

2011年(53)

2010年(33)

2009年(32)

分类: Python/Ruby

2011-03-25 13:01:46

  1. #coding=utf-8
  2. from twisted.internet import reactor
  3. from twisted.internet.protocol import ServerFactory
  4. from twisted.protocols.basic import LineOnlyReceiver

  5. class ChatProtocol(LineOnlyReceiver):

  6.     name = ""

  7.     def getName(self):
  8.         if self.name!="":
  9.             return self.name
  10.         return self.transport.getPeer().host

  11.     def connectionMade(self):
  12.         print "New connection from "+self.getName()
  13.         self.sendLine("Send '/NAME [new name]' to change your name.")
  14.         self.sendLine("Send '/EXIT' to quit.")
  15.         self.factory.sendMessageToAllClients(self.getName()+" has joined the party.")
  16.         self.factory.clientProtocols.append(self)

  17.     def connectionLost(self, reason):
  18.         print "Lost connection from "+self.getName()
  19.         self.factory.clientProtocols.remove(self)
  20.         self.factory.sendMessageToAllClients(self.getName()+" has disconnected.")

  21.     def lineReceived(self, line):
  22.         print self.getName()+": "+line
  23.         if line[:5]=="/NAME":
  24.             oldName = self.getName()
  25.             self.name = line[5:].strip()
  26.             self.factory.sendMessageToAllClients(oldName+" changed name to "+self.getName())
  27.         elif line=="/EXIT":
  28.             self.transport.loseConnection()
  29.         else:
  30.             self.factory.sendMessageToAllClients(self.getName()+": "+line)

  31.     def sendLine(self, line):
  32.         self.transport.write(line+"\r\n")

  33. class ChatProtocolFactory(ServerFactory):

  34.     protocol = ChatProtocol

  35.     def __init__(self):
  36.         self.clientProtocols = []

  37.     def sendMessageToAllClients(self, mesg):
  38.         for client in self.clientProtocols:
  39.             client.sendLine(mesg)

  40. print "Starting Server"
  41. factory = ChatProtocolFactory()
  42. reactor.listenTCP(3001, factory)
  43. reactor.run()
阅读(851) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~