python代码分享群_实现tcp socket群聊功能

[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

694748ed64b9390909c0d88230893790.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值