2014-10-29 46 views
1

扭曲的支持是否会同时监听多个端口,具有不同的“处理程序”(不同的每个端口的回调集)?实质上,我希望我的进程在一个进程中托管两台服务器,每台服务器执行不同的功能。我需要使用两个反应器来做到这一点吗?与多个端口,协议和反应器扭曲

回答

2

是,例如,修改quote server example你可以添加第二个实例监听不同的端口上使用不同的报价:

from twisted.internet.protocol import Factory, Protocol 
from twisted.internet.endpoints import TCP4ServerEndpoint 
from twisted.internet import reactor 

class QOTD(Protocol): 

    def connectionMade(self): 
     # self.factory was set by the factory's default buildProtocol: 
     self.transport.write(self.factory.quote + '\r\n') 
     self.transport.loseConnection() 


class QOTDFactory(Factory): 

    # This will be used by the default buildProtocol to create new protocols: 
    protocol = QOTD 

    def __init__(self, quote=None): 
     self.quote = quote or 'An apple a day keeps the doctor away' 

endpoint = TCP4ServerEndpoint(reactor, 8007) 
endpoint.listen(QOTDFactory("configurable quote")) 

endpoint2 = TCP4ServerEndpoint(reactor, 8008) 
endpoint2.listen(QOTDFactory("another configurable quote")) 

reactor.run() 

输出:

$ nc localhost 8007 
configurable quote 
$ nc localhost 8008 
another configurable quote 
+0

真棒答案。如果我想抛出其他东西,比如扭曲的WebSocket,那么怎么办?我可以和那些一起做吗? – 2014-10-29 01:43:38

+1

@horsehair我没有尝试过,但它应该可以正常工作。反应堆基本轮询每个插座,并在数据到达时将数据发送到相应的协议。你在使用http://autobahn.ws/? – 2014-10-29 01:47:48

+0

我想确定我是否应该使用autobahn.ws,但我开始认为Twister内置了使用高速公路以外的功能。对于一个简单的只传递消息的WebSocket来说,至少。没有? – 2014-10-29 02:02:52