用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

实现tcp socket群聊功能

2021-02-15 作者:gaojiawei举报

[python]代码库

import threading
import time
import logging
import socket

logging.basicConfig(format='%(thread)s %(threadName)s %(message)s',level=logging.INFO)

class ChatServer:
    def __init__(self,ip='127.0.0.1',port=9999):
        self.sock = socket.socket()
        self.addr = (ip,port)
        self.clients = {}
        self.event = threading.Event()
    def start(self):
        self.sock.bind(self.addr)
        self.sock.listen()
        threading.Thread(target=self._accept,name='accept').start()
    def stop(self):
        for c in self.clients.values():
            c.close()
        self.sock.close()
        self.event.wait(3)
        self.event.set()
    def _accept(self):
        while not self.event.is_set():
            conn,client = self.sock.accept()   #阻塞
            self.clients[client] = conn   #ip + port

            threading.Thread(target=self._recv,args=(conn,client),name='{}-recv'.format(client)).start()
    def _recv(self,conn,client):
    #接收到了数据,然后分发
        while not self.event.is_set():
            try:
                data = conn.recv(1024)
            except Exception as e:
                logging.info(e)
                data = b"quit"

            data = data.decode()
            logging.info(data)
            #客户端通知,退出机制
            if data == "quit":
                logging.info('``````quit````')
                self.clients.pop(client)

                conn.close()
                break

            msg = 'ack {}'.format(data)

            for conn in self.clients.values():
                conn.send(msg.encode())  # 发送给客户端消息,data是字节

cs = ChatServer()
cs.start()

e = threading.Event()

def showthreads():
    while not e.wait(3):
        logging.info(threading.enumerate())

threading.Thread(target=showthreads,name='showthread',daemon=True).start()

while True:
    cmd = input(">>>").strip()
    if cmd == 'quit':
        cs.stop()
        break


分享到:
更多

网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。