开发者

Python TCP Client to Client message forwarding

开发者 https://www.devze.com 2023-04-11 02:52 出处:网络
I am looking for a short example in python of a TCP server passing an incoming client message to another new client. All I could find was examples on echo server/clients.

I am looking for a short example in python of a TCP server passing an incoming client message to another new client. All I could find was examples on echo server/clients.

Cheer开发者_JAVA技巧s,

dhpizza


Here's a basic example using only standard libraries:

import SocketServer
import threading

class Handler(SocketServer.StreamRequestHandler):

    def handle(self):
        print self.client_address,'connected'
        self.server.add_client(self.request)
        while 1:
            data = self.request.recv(1024)
            if not data: break
            self.server.send(self.request,data)
        self.server.remove_client(self.request)

class Server(SocketServer.ThreadingTCPServer):

    def __init__(self,*args,**kwargs):
        SocketServer.ThreadingTCPServer.__init__(self,*args,**kwargs)
        self.clients = []
        self.lock = threading.Lock()

    def add_client(self,c):
        with self.lock:
            self.clients.append(c)

    def remove_client(self,c):
        with self.lock:
            self.clients.remove(c)

    def send(self,sender,data):
        with self.lock:
            for c in self.clients:
                if c is not sender:
                    c.sendall(data)

s = Server(('',8000),Handler)
s.serve_forever()
0

精彩评论

暂无评论...
验证码 换一张
取 消