Python 之socketserver模块实现多线程

2021-02-14 05:18

阅读:620

标签:pre   ini   ever   rev   request   and   port   ctime   div   

一、服务端

import socketserver
import time

conn_poll = []

class MyServer(socketserver.BaseRequestHandler):
    
    def handle(self):
        print(... connected from {}.format(self.client_address))
        conn_poll.append(self.client_address)
        while True:
            # request.recv 方法接收客户端发来的消息
            data = self.request.recv(1024)
            
            if data == exit:
                conn_poll.remove(self.client_address)
                # 发送exit给客户端断开连接
                self.request.sendall(data.encode(utf-8))
                break
            # request.sendall 方法发送消息给客户端
            self.request.sendall([{}] {}.format(time.ctime(), data.decode(utf-8)).encode(utf-8))
        
    def finish(self):
        print(finish)
        
    
if __name__ == __main__:
    s = socketserver.ThreadingTCPServer((‘‘, 12306), MyServer)
    s.serve_forever()

 

Python 之socketserver模块实现多线程

标签:pre   ini   ever   rev   request   and   port   ctime   div   

原文地址:https://www.cnblogs.com/yang-2018/p/12723952.html


评论


亲,登录后才可以留言!