一下是聊天服务端代码:(实现广播)
- #! /usr/bin/env python
- #coding=utf-8
-
- from twisted.internet import protocol
- from twisted.protocols import basic
- from twisted.python import log
- from twisted.internet import reactor
- import sys
-
- class ConfigServer(basic.LineReceiver):
- def __init__(self):
- pass
-
- def lineReceived(self, line):
- if line == 'quit':
- self.sendLine("Goodbye.")
- self.transport.loseConnection()
- else:
- self.broadcast(line)
-
- def broadcast(self, msg):
- for client in self.factory.clients:
- client.sendLine("someone said: %s" % msg);
-
- def connectionMade(self):
- self.factory.clients.append(self)
- print "Connect from %s.." % self.transport.getHost()
- self.sendLine("Welcome...%s" % self.transport.getHost())
-
- def connectionLost(self, reason):
- self.factory.clients.remove(self)
- # self.sendLine("Disconnect...%s" % self.transport.getHost())
- pass
-
- class ConfigServerFactory(protocol.ServerFactory):
- protocol = ConfigServer
- clients = []
-
- def main():
- log.startLogging(sys.stdout)
- reactor.listenTCP(8080,ConfigServerFactory())
- reactor.run()
-
- if __name__ == '__main__':
- main()