tkinter+socket 库初步实现聊天服务端,运行效率奇低,仅供参考
tkinter+socket 库初步实现聊天服务端,运行效率奇低,仅供参考
1 import threading as tr 2 import socket as sk 3 import time as timeset 4 import tkinter as tk 5 6 #全局变量----------------------------------------------------------------------- 7 8 textvar_global = "" 9 sendvar_global = "" 10 11 #全局变量----------------------------------------------------------------------- 12 13 #服务器建立与处理模块部分start----------------------------------------------------- 14 def senddata(sock ,addr): #数据发送模块 15 global sendvar_global 16 while True: 17 if sendvar_global!="": 18 sock.send(sendvar_global.encode(encoding = "utf-8"))#转码二进制 19 sendvar_global="" 20 timeset.sleep(1) 21 def readdata(sock ,addr): #数据读取模块 22 global textvar_global 23 while True: 24 data = sock.makefile().readline() #转换为文件字符串 25 if data != "": 26 print(data) 27 textvar_global = data 28 timeset.sleep(0.3) 29 30 def server_start(backlog = 5): #socket服务创建与监听 31 sev = sk.socket(sk.AF_INET ,sk.SOCK_STREAM) 32 sev.bind(('10.238.2.208',2333)) #作为服务端进行ip端口监听 33 sev.listen(backlog) #监听的线程数量 34 while True: 35 sock,addr = sev.accept() #accept()函数带阻塞 36 print(addr) 37 thread1 = tr.Thread(target=senddata,args=(sock,addr)) #传参到发送模块 38 thread2 = tr.Thread(target=readdata,args=(sock,addr)) #传参到接收模块 39 thread1.start() 40 thread2.start() 41 #服务器建立与处理模块部分end----------------------------------------------------- 42 43 #UI界面部分start---------------------------------------------------------------- 44 def send_var_refresh(send_var): #按键处理函数 45 global sendvar_global 46 sendvar_global = send_var 47 48 def window_creat(): 49 50 global textvar_global #变量 51 global sendvar_global 52 window = tk.Tk() 53 window.title("ok?") 54 window.geometry('200x200') 55 label_var = tk.StringVar() 56 label_var.set(textvar_global) 57 58 label_read = tk.Label(window,textvariable=label_var,width = 8,height =2,bg ='green') 59 label_read.pack() 60 61 entry_send = tk.Entry(window,show=None) 62 entry_send.pack() 63 64 button_send = tk.Button(window,text="send",width=15,height=2,command=lambda :send_var_refresh(entry_send.get()))#lanba 实现传参 65 button_send.pack() 66 while True: 67 label_var.set(textvar_global) 68 label_read.update() #更新标签 69 timeset.sleep(1) 70 71 window.mainloop() 72 #UI界面部分end----------------------------------------------------------------- 73 def winandsock_start(): 74 win_thread = tr.Thread(target=window_creat) 75 sock_thread =tr.Thread(target=server_start) 76 win_thread.start() 77 sock_thread.start() 78 79 winandsock_start()
运行服务端
客户端情况