Python之socketserver

Posted 亚洲哈登

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之socketserver相关的知识,希望对你有一定的参考价值。

import threading
from socketserver import ThreadingTCPServer,BaseRequestHandler
import sys
import logging

FORMAT = %(asctime)s %(threadName)d %(thread)d %(message)s
logging.basicConfig(level=logging.INFO,format=FORMAT)

class ChatHandler(BaseRequestHandler): #一对一,相当于receive函数
    clients = {}

    def setup(self):
        self.event = threading.Event()
        self.clients[self.client_address] = self.request
    def finish(self):
        self.clients.pop(self.client_address)
        self.event.set()

    def handle(self):
        print(self.request) #new_socket 用来recv
        while not self.event.is_set():
            data = self.request.recv(1024)
            print(data,self.client_address)
            msg = {}.ack.format(data).encode()
            #如何实现一对多,多在哪里,如何获得
            for c in self.clients.values():
                c.send(msg)
addr = (0.0.0.0,9999)
server = ThreadingTCPServer(addr,ChatHandler)  #相当于tcp总的socket
print(server)
t = threading.Thread(target=server.serve_forever,name=chatserver)
t.start()
try:
    while True:
        cmd = input(">>>")
        if cmd.strip() == quit:
            break
except Exception as e:
    print(e)
except KeyboardInterrupt:
    pass
finally:
    print(exit)
    sys.exit(0)

 

以上是关于Python之socketserver的主要内容,如果未能解决你的问题,请参考以下文章

Python之socketserver

Python 之socketserver模块实现多线程

Python实战之SocketServer模块

Python网络编程之socketserver实现多并发

python基础之socket与socketserver

python基础之socket与socketserver