Twisted中TCP服务器的问题
我正在尝试使用Twisted创建一个简单的TCP服务器,这个服务器可以让不同的客户端之间进行一些互动。下面是主要的代码:
#!/usr/bin/env python
from twisted.internet import protocol, reactor
from time import ctime
#global variables
PORT = 22334
connlist = {} #store all the connections
ids = {} #map the from-to relationships
class TSServerProtocol(protocol.Protocol):
def dataReceived(self, data):
from_id,to_id = data.split('|') #get the IDs from standard client input,which looks like "from_id|to_id"
if self.haveConn(from_id): #try to store new connections' informations
pass
else:
self.setConn(from_id)
self.setIds(from_id,to_id)
if to_id in self.csids.keys():
self.connlist[to_id].transport.write(\
"you get a message now!from %s \n" % from_id) #if the to_id target found,push him a message.doesn't work as expected
def setConn(self,sid):
connlist[sid] = self
#some other functions
factory = protocol.Factory()
factory.protocol = TSServerProtocol
print 'waiting from connetction...'
reactor.listenTCP(PORT, factory)
reactor.run()
正如注释所提到的,如果有新的客户端连接进来,我会把它的连接信息存储在一个全局变量connlist
中,结构大概是这样的:
connlist = {a_from_id:a_conObj,b_from_id:b_conObj,....}
然后我会解析输入信息,并把它的发送和接收信息映射到ids
中。接着,我会检查ids
中是否有一个键和当前的“to_id”匹配。如果匹配,就用connlist[to_id]
获取连接信息,并把消息推送到目标连接上。但是这并没有成功。消息只在同一个连接中显示。希望有人能给我一些方向。
谢谢!
1 个回答
3
每当建立一个TCP连接时,Twisted会创建一个独特的