106-基于多进程的时间消息服务器

1、支持多客户端同时访问
2、客户端向服务器发送消息后,服务器把消息加上时间发回客户端
3、每个客户端断开后会产生僵尸进程,新客户端连接时销毁所有的僵尸进程

import socket
import os
from time import strftime

class TcpTimeServer:
    def __init__(self, host='', port=12345):
        self.addr = (host, port)
        self.serv = socket.socket()
        self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind(self.addr)
        self.serv.listen(1)

    def chat(self, c_sock):
        while True:
            data = c_sock.recv(1024)
            if data.strip() == b'quit':
                break
            data = '[%s] %s' % (strftime('%H:%M:%S'), data.decode('utf8'))
            c_sock.send(data.encode('utf8'))
        c_sock.close()

    def mainloop(self):
        while True:
            cli_sock, cli_addr = self.serv.accept()
            pid = os.fork()
            if pid:
                cli_sock.close()
                while True:
                    result = os.waitpid(-1, 1)[0]  # waitpid会优先处理僵尸进程
                    if result == 0:
                        break
            else:
                self.serv.close()
                self.chat(cli_sock)
                exit()

        self.serv.close()

if __name__ == '__main__':
    s = TcpTimeServer()
    s.mainloop()
    原文作者:凯茜的老爸
    原文地址: https://www.jianshu.com/p/0c45df7ec53a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞