Python一对一聊天室(简易版)

发布时间:2025-12-09 20:01:24 浏览次数:4

服务端

# coding=utf-8import tkinter as tkimport timeimport socketimport threading# 服务端发送的消息def Send_Message():result = GulSlk.get("1.0", "end")sock.send(result.encode())theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())GulListBox.insert("end", "服务端" + " " + theTime + ":")GulListBox.insert("end", " " + result)GulSlk.delete("1.0", "end")# 接收客户端消息def Receive_Message(sock,addr):while True:info=sock.recv(1024).decode()theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())GulListBox.insert("end", "客户端" + " " + theTime + ":")GulListBox.insert("end", " " + info)def Sever_init(sock,addr):print("客户端接入成功")Threading_one = threading.Thread(target=Receive_Message, args=(sock,addr))Threading_one.daemon = TrueThreading_one.start()if __name__ == '__main__':window = tk.Tk()window.geometry('600x600')window.title('服务端')GulListBox = tk.Listbox(window, width=120, height=20)GulListBox.pack()GulButton = tk.Button(window, width=10, text="发送", command=Send_Message)GulButton.place(x=518, y=567)GulSlk = tk.Text(window, width=120, height=10)GulSlk.place(x=10, y=400)host = socket.gethostname()post = 20222s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((host, post))s.listen(2)print("等待客户端连接")sock, addr = s.accept()threading1=threading.Thread(target=Sever_init,args=(sock,addr))threading1.start()window.mainloop()

客户端

# coding=utf-8import tkinter as tkimport timeimport socketimport threading# 服务端发送的消息def Send_Message():result = GulSlk.get("1.0", "end")s.send(result.encode())theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())GulListBox.insert("end", "客户端" + " " + theTime + ":")GulListBox.insert("end", " " + result)GulSlk.delete("1.0", "end")# 接收消息def Sever_Threading(s):while True:info=s.recv(1024).decode()theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())GulListBox.insert("end", "服务端" + " " + theTime + ":")GulListBox.insert("end", " " + info)def Client(s):s.connect((host, post))print('连接成功')Threading_one = threading.Thread(target=Sever_Threading, args=(s,))Threading_one.daemon = TrueThreading_one.start()if __name__ == '__main__':window = tk.Tk()window.geometry('600x600')window.title('客户端')GulListBox = tk.Listbox(window, width=120, height=20)GulListBox.pack()GulButton = tk.Button(window, width=10, text="发送", command=Send_Message)GulButton.place(x=518, y=567)GulSlk = tk.Text(window, width=120, height=10)GulSlk.place(x=10, y=400)host = socket.gethostname()post = 20222s = socket.socket()threding1=threading.Thread(target=Client,args=(s,))threding1.start()window.mainloop()

唯一缺点 就是要等客户端接收了服务端的页面才能弹出。如果你们有能力自己稍微改进一下

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477