Websocket / TCP代理与高速公路和扭曲

时间:2013-06-25 20:32:37

标签: twisted

我正在尝试用高速公路编写代理并扭曲。当websocket客户端连接时,我想打开到服务器的TCP连接。我似乎无法弄清楚如何将通过TCP连接接收的数据传递回websocket客户端。

#!/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()

1 个答案:

答案 0 :(得分:0)

在您的WSServerProtocol类中,在onMessage线程中:

def onMessage(self, msg, binary):
    self.sendMessage(msg)