views:

72

answers:

2

Dear all, I need to implement a TCP server in Python which receives some data from a client and then sends this data to another client. I've tried many different implementations but no way to make it run. Any help would be really appreciated.
Below is my code:

import SocketServer
import sys
import threading

buffer_size = 8182
ports = {'toserver': int(sys.argv[1]), 'fromserver': int(sys.argv[2])}

class ConnectionHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        # I need to send the data received from the client connected to port 'toserver'
        # to the client connected to port 'fromserver' - see variable 'ports' above

class TwoWayConnectionServer(threading.Thread):

    def __init__(self):
        self.to_server = SocketServer.ThreadingTCPServer(("", ports['toserver']), ConnectionHandler)
        self.from_server = SocketServer.ThreadingTCPServer(("", ports['fromserver']), ConnectionHandler)
        threading.Thread.__init__(self)

    def run(self):
        while (1):
            self.to_server.handle_request()
            self.from_server.handle_request()

def serve_non_blocking():

    server = TwoWayConnectionServer()
    server.run()

if __name__ == '__main__':

    serve_non_blocking()
A: 

Can you be more specific about what you tried and what didn't work? There are lots of ways to do this. Probably the easiest would be to use the socket library - maybe looking at some examples will help:

http://docs.python.org/library/socket.html#example

samtregar
See the code I added to my question...
+1  A: 

See the Twisted tutorial, and also twisted.protocols.portforward. I think that portforward module does something slightly different from what you want, it opens an outgoing connection to the destination port rather than waiting for the second client to connect, but you should be able to work from there.

keturn
I've added some code to my question (see above). For instance, is it possible to receive data from one client (port 'toserver') and forward it to another client (port 'fromserfver') directly? Or is it necessary to buffer incoming data and the send it to the target client as soon as the target client sends a message that asks for this data? Thanks, Jeff
I guess you might want to buffer if there's nothing connected to `from_server` at first, but otherwise your handler on `to_server` can just look like `def dataReceived(self, data): from_server.write(data)`.
keturn