親愛的所有人,我需要在Python中實現一個TCP服務器,它從客戶端接收一些數據,然後將這些數據發送到另一個客戶端。我嘗試了許多不同的實現,但沒有辦法讓它運行。任何幫助將非常感激。
下面是我的代碼:如何在Python中實現集線器
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()
你需要更具體。你是什麼意思「讓它運行」?你不能啓動程序嗎? – unwind 2010-03-22 16:24:44