编程语言
首页 > 编程语言> > 网络编程之TCP多人聊天

网络编程之TCP多人聊天

作者:互联网

服务端转发信息:

from socket import *
from threading import Thread
sockets=[]
def main():
    server_socket=socket(AF_INET,SOCK_STREAM)
    server_socket.bind(('',9999))
    server_socket.listen()
    while True:
        client_socket,client_info=server_socket.accept()
        sockets.append(client_socket)
        t=Thread(target=readMsg,args=(client_socket,))
        t.start()
def readMsg(client_socket):
    while True:
        recv_date=client_socket.recv(1024)
        if recv_date.decode('utf-8').endswith('bye'):
            sockets.remove(client_socket)
            break
        if len(recv_date)>0:
            for socket in sockets:
                socket.send(recv_date)
main()

客户端1:

from socket import *
from threading import Thread
flag=True
def readMsg(client_socket):
    while flag:
        recv_data=client_socket.recv(1024)
        print('收到:',recv_data.decode('utf-8'))
def writeMsg(client_socket):
    global flag
    while flag:
        msg=input('>')
        mag=username+'说:'+msg
        client_socket.send(mag.encode('utf-8'))
        if mag.endswith('bye'):
            flag=False
            break
client_socket=socket(AF_INET,SOCK_STREAM)
client_socket.connect(('192.168.64.1',9999))
username=input('请输入用户名:')
t1=Thread(target=readMsg,args=(client_socket,))
t1.start()
t=Thread(target=writeMsg,args=(client_socket,))
t.start()
t1.join()
t.join()
client_socket.close()

标签:socket,Thread,编程,TCP,flag,client,聊天,recv,sockets
来源: https://blog.csdn.net/kai0511/article/details/116654954