如何用Python实现hub

2024-09-25 06:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

亲爱的各位,我需要用Python实现一个TCP服务器,它从客户端接收一些数据,然后将这些数据发送到另一个客户端。我尝试过许多不同的实现,但没有办法让它运行。如有任何帮助,我们将不胜感激。
以下是我的代码:

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()

Tags: thetofromimportselfserverdefsys
2条回答

请参见Twisted tutorial,以及{a2}。我认为portforward模块所做的与您想要的稍有不同,它将打开一个到目标端口的传出连接,而不是等待第二个客户端连接,但是您应该能够从那里开始工作。在

你能更具体地说一下你试过什么,什么没用吗?有很多方法可以做到这一点。可能最简单的方法是使用socket库-也许看一些示例会有所帮助:

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

相关问题 更多 >