Chinaunix
标题:
谁能提供一下简单的基于twisted的聊天室代码吗?
[打印本页]
作者:
xmichen
时间:
2007-04-03 09:01
标题:
谁能提供一下简单的基于twisted的聊天室代码吗?
谁能提供一下简单的基于twisted的聊天室代码吗?
基于telnet服务的
只要最简单的就好了,监听一个端口,接受CLIENT连接
每个CLIENT连接的时候,向所有已经连接的CLIENT broardcast一个某某登陆的消息
下面是参考网上的文章写的,但不知道如何实现broardcast消息。。
原想在connectionMade里面增加一个LIST记录所有客户端
好象也不行,,请指教
#!/usr/local/python24/bin/python
#-*- encoding:gb2312 -*-
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.sendLine("You said: %s" % line)
def connectionMade(self):
print "Connect from %s.." % self.transport.getHost()
self.sendLine("Welcome...%s" % self.transport.getHost())
def connectionLost(self,reason):
pass
class ConfigServerFactory(protocol.ServerFactory):
protocol=ConfigServer
def main():
log.startLogging(sys.stdout)
reactor.listenTCP(8080,ConfigServerFactory())
reactor.run()
if __name__ == '__main__':
main()
复制代码
作者:
xmichen
时间:
2007-04-03 16:57
研究出来了,,请指教。。
#!/usr/local/python24/bin/python
#-*- encoding:gb2312 -*-
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()
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2