1
autobahn과 twisted와 함께 프록시를 작성하려고합니다. websocket 클라이언트가 연결될 때 서버에 대한 TCP 연결을 열고 싶습니다. 알아낼 수없는 것은 TCP 연결을 통해받은 데이터를 websocket 클라이언트로 다시 전달하는 방법입니다. 의 onMessage 스레드에 WSServerProtocol 클래스autobahn과 twisted가있는 Websocket/TCP 프록시
#!/usr/bin/env python
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import Int32StringReceiver
from twisted.internet import reactor
from twisted.python import log
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
import sys
class ServerClient(Int32StringReceiver):
structFormat = "!I"
def __init__(self):
self.filter = "{\"exporterip\": \"1.2.3.4\"}"
def connectionMade(self):
self.sendString(self.filter)
def stringReceived(self, string):
print "Received data %s" % (string)
class ServerClientFactory(ClientFactory):
protocol = ServerClient
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
class WSServerProtocol(WebSocketServerProtocol):
def onOpen(self):
print "Websocket connection opened"
tcpfactory = ServerClientFactory()
reactor.connectTCP('localhost', 9876, tcpfactory)
def onClose(self):
print "Websocket connection closed"
def onMessage(self, msg, binary):
print "Websocket message received"
def main():
log.startLogging(sys.stdout)
wsfactory = WebSocketServerFactory("ws://localhost:9000", debug = False)
wsfactory.protocol = WSServerProtocol
listenWS(wsfactory)
reactor.run()
if __name__ == '__main__':
main()