2014-10-29 54 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