Python 网络编程 socket 简易聊天窗
发布于: 2020 年 05 月 11 日
Python网络编程socket 简易聊天窗
涉及 socket,tkinter,threading
Python网络编程socket 简易聊天窗
涉及 socket,tkinter,threading
Python网络编程socket 简易聊天窗
涉及 socket,tkinter,threading
server端
import socketimport tkinter as tkfrom threading import Threadsk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)sk.bind(("127.0.0.1",10010))sk.listen()# 准备接受连接print('准备完毕----------')conn,address = sk.accept()print('客户端连接成功')# 创建窗口win = tk.Tk()win.title('聊天窗口')win.geometry('500x300')msg_box = tk.Text(win) #文本域var = tk.Variable()tf = tk.Entry(win,textvariable=var) # 用户输入文本框# 简单布局msg_box.pack(side = tk.TOP,fill=tk.X)tf.pack(side=tk.BOTTOM,fill=tk.X)def func(event): s = var.get() conn.send(s.encode("utf-8")) print(s) var.set("")tf.bind("<KeyPress-Return>", func)def recv(): while 1: msg_bytes = conn.recv(1024) s = msg_bytes.decode('utf-8') msg_box.insert(tk.END, s+"\n")t = Thread(target=recv)t.start()win.mainloop()conn.close()sk.close()
client端
import socketimport tkinter as tkfrom threading import Threadsk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)print('准备连接服务器')sk.connect(("127.0.0.1",10010))print('连接成功')# 创建窗口win = tk.Tk()win.title('聊天窗口222')win.geometry('500x300')msg_box = tk.Text(win) #文本域var = tk.Variable()tf = tk.Entry(win,textvariable=var) # 用户输入文本框# 简单布局msg_box.pack(side = tk.TOP,fill=tk.X)tf.pack(side=tk.BOTTOM,fill=tk.X)def func(event): s = var.get() sk.send(s.encode("utf-8")) print(s) var.set("")tf.bind("<KeyPress-Return>", func)def recv(): while 1: msg_bytes = sk.recv(1024) s = msg_bytes.decode('utf-8') msg_box.insert(tk.END, s+"\n")t = Thread(target=recv)t.start()win.mainloop()sk.close()
划线
评论
复制
发布于: 2020 年 05 月 11 日阅读数: 57
Flychen
关注
日拱一卒! 2020.02.21 加入
还未添加个人简介
评论