majidarif
majidarif

Reputation: 20105

Proxy Server with Python Twisted

I'm trying to write a proxy server that does a few things:

  1. Receive data from client.
  2. Validate data.
  3. Forward data to server.
  4. Receive data from server immediately send back to client.

In node.js I can do #4 with server.pipe(client). Is there a similar trick in twisted?

What I have:

class Player(protocol.Protocol):

    def __init__(self):
        self.server_connection = reactor.connectTCP('192.168.254.101', 1000, GateFactory())
...

class Gate(protocol.Protocol):

    def dataReceived(self, recd):
        print recd
...

class GateFactory(protocol.ClientFactory):

    def buildProtocol(self):
        return Gate()
...

class PlayerFactory(protocol.Factory):

    def __init__(self):
        self.players = {}

    def buildProtocol(self, addr):
        return Player(self.players)

...

reactor.listenTCP(1000, PlayerFactory())

My problem

I forward the data to the server by doing:

self.gate_connection.transport.write(packet)

But how do I forward the response to the client from:

class Gate(protocol.Protocol):

    def dataReceived(self, recd):
        print recd

Upvotes: 1

Views: 452

Answers (1)

Glyph
Glyph

Reputation: 31910

When you construct GateFactory, you need to pass it a reference to self (the Player instance) which GateFactory can then pass on to its Gate instances when it creates them in buildProtocol.

(Also, please consider using HostnameEndpoint rather than connectTCP directly.)

Upvotes: 1

Related Questions