[Twisted-Python] Simple gateway server

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sat Feb 6 08:37:05 MST 2010


On 06:30 am, sleeepd at gmail.com wrote:
>I need to write a gateway server that forwarding data between client 
>and
>data server002I use a Protocol instance for incoming connection from 
>client,
>and creating another Protocol instance to connect data server when 
>received
>data from client:

You can find an example of this in Twisted itself:

http://twistedmatrix.com/trac/browser/trunk/twisted/protocols/portforward.py
>
>Exp.1
>...
>Class ToClientProtocol(Protocol):
>""" Protocol for incoming connection from client. """
>
>    def connectionMade(self):
>
>        self.data_server = reactor.connectTCP('localhost', 8888,
>DataServerFactory())        # make connection to data server
>
>        self.data_server.transport.write('hello!')         # send a 
>message
>to data server, but not work
>...

Right.  data_server has no transport attribute.  reactor.connectTCP 
doesn't return a protocol, it returns a "connector", which is really not 
useful for very much.  The main thing you can do with it is cancel the 
connection attempt.
>
>The connetion to data server can be made, BUT the data server received
>nothing. self.data_server.transport.write() not work.
>
>It will work if I write like that:
>Exp. 2
>...
>Class ToClientProtocol(Protocol):
>""" Protocol for incoming connection from client. """
>
>    def connectionMade(self):
>
>        self.data_server = reactor.connectTCP('localhost', 8888,
>DataServerFactory(self))        # make connection to data server
>
>Class DataServer(Protocol):
>""" Protocol for connection to data server. """
>
>    def __init__(self, client):
>        self.client = client
>
>    def connectionMade(self):
>        self.client.data_server.transport.wirte('hello!')        # send
>message to data server, it's work now!
>
>Class DataServerFactory(self):
>
>    def __init__(self, client):
>        self.client = client
>
>    def buildProtocol(self, addr):
>        return DataServer(self.client)
>...
>
>I don't think this is the best way. Why I can't simply wirte like 
>Exp.1?

Actually this is a better way.  What in particular do you think is bad 
about it?

Jean-Paul




More information about the Twisted-Python mailing list