码迷,mamicode.com
首页 > 编程语言 > 详细

Python之socketserver

时间:2018-06-18 23:18:49      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:add   for   base   pre   oar   value   rip   star   _for   

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

标签:add   for   base   pre   oar   value   rip   star   _for   

原文地址:https://www.cnblogs.com/harden13/p/9196587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!