实例:Python实现聊天室

废话不多说,直接上代码
服务端:

import socket
from threading import Thread

client_dict = {}

def brodcast(msg,nikename = ''):
    for khd_socket in client_dict.values():
        khd_socket.send(bytes(nikename.encode('gbk') + msg + b'\n'))

def chat(khd_socket:socket.socket):
    try:
        nikename = khd_socket.recv(1024).decode('gbk')
        welcome = f'欢迎{nikename}加入聊天室\n'
        client_dict[nikename] = khd_socket
        brodcast(welcome.encode('gbk'))
        while True:
            try:
                msg = khd_socket.recv(1024)
                brodcast(msg,nikename + ':')
            except:
                khd_socket.close()
                del client_dict[nikename]
                brodcast(bytes(f'{nikename}离开聊天室\n','gbk'))
    except:
        print('客户端断开连接')

if __name__ == '__main__':
    tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
    tcp.bind(("",9090))
    print(f'服务器已开启,正在等待用户进入...')
    tcp.listen(127)
    while True:
        try:
            khd_socket, ip = tcp.accept()
            print(f'{ip}建立连接')
            khd_socket.send('欢迎加入聊天室,输入昵称开始聊天\n'.encode('gbk'))
            khd_thread = Thread(target=chat,args=(khd_socket,))
            khd_thread.daemon = True
            khd_thread.start()
        except:
            print('客户端断开连接')
    tcp.close()

客户端(GUI):

import socket
from tkinter import Tk, Frame, Text, Button, END
from threading import Thread

windows = Tk()
windows.title('聊天室')

message_frame = Frame(width=480,height=300,bg='white')
text_frame = Frame(width=480,height=100)
send_frame = Frame(width=480,height=30)

tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp.connect(('127.0.0.1',9090))

def get_msg():
    while True:
        try:
            msg = tcp.recv(1024)
            text_message.insert(END,msg.decode('gbk'))
        except:
            break

def send():
    send_msg = text_text.get('0.0',END)
    if send_msg.endswith('\n'):
        send_msg = send_msg[:-1]
    tcp.send(send_msg.encode('gbk'))
    text_text.delete('0.0',END)

text_message = Text(message_frame)
text_text = Text(text_frame)
button_send = Button(send_frame,text='发送',command=send)

message_frame.grid(row=0,column=0,padx=3,pady=6)
text_frame.grid(row=1,column=0,padx=3,pady=6)
send_frame.grid(row=2,column=0)

message_frame.grid_propagate(0)
text_frame.grid_propagate(0)
send_frame.grid_propagate(0)

text_message.grid()
text_text.grid()
button_send.grid()

msg_thread = Thread(target=get_msg)
msg_thread.start()

windows.mainloop()
posted @ 2020-08-15 22:35  小宇宙zjy  阅读(814)  评论(0编辑  收藏  举报