最简单的Python群聊

server:

import socket
from threading import Thread

conn_lst=[]

sk=socket.socket()

sk.bind(("127.0.0.1",9999))
sk.listen()


def waitMsg(conn):
    while 1:
        msg=conn.recv(1024)
        for i in conn_lst:
            i.send(msg.upper())

while 1:
    conn,addr=sk.accept()
    conn_lst.append(conn)
    t=Thread(target=waitMsg,args=(conn,))
    t.start()

 client:

import socket
from threading import Thread

sk = socket.socket()

sk.connect(("127.0.0.1",9999))

def waitMsg():
    while 1:
        msg=sk.recv(1024)
        print(msg)

def pushMsg():
    while 1:
        msg = input(">>>")
        sk.send(msg.encode("utf-8"))

tWaitMsg=Thread(target=waitMsg)
tWaitMsg.start()

tSendMsg=Thread(target=pushMsg)
tSendMsg.start()

启动 server 启动多个 client 即可多个客户端同时收到消息

posted @ 2019-07-25 18:34  码农丁  阅读(541)  评论(0编辑  收藏  举报