在此基础上加入GUI可视化界面超链接
客户端
#搭建框架
import time
import socket
import threading
from tkinter import *
sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tot=0
def zjm(name):
sk.connect(('192.168.19.74',7777))#连接服务器
sk.send(name.encode('utf-8'))#传名字
def hq():
global tot
while 1:
date=sk.recv(1024).decode('utf-8')
tot+=1
print('接受到了来自服务器的信息')
msg.config(state='normal')
msg.insert(END,date+'\n')
msg.config(state='disabled')
def hk():
msg.config(state='normal')
msg.delete('0.0','end')
msg.config(state='disabled')
def fs():
date=sed.get()
sed.delete(0, END)
if len(date):
print('触发发送功能:',date)
sk.send(date.encode('utf-8'))
t=threading.Thread(target=hq)
t.setDaemon(1)
t.start()
global app
app.destroy()
win=Tk()
win.title(name)
win.geometry('500x500')
msg_Frame=Frame(win,width=300,height=460)
sed_Frame=Frame(win,width=300,height=460)
bot_Frame=Frame(win,width=300,height=460)
msg=Text(msg_Frame,state='disabled',width=50)
sed=Entry(sed_Frame,width=100)
bot=Button(bot_Frame,text='发送',bg='red',command=fs)
bot2=Button(bot_Frame,text='清空',bg='green',command=hk)
msg.pack()
sed.pack()
bot.pack()
bot2.pack()
msg_Frame.pack(padx=6,pady=10)
sed_Frame.pack(padx=6,pady=10)
bot_Frame.pack(padx=6,pady=10)
win.mainloop()
if __name__ == '__main__':
def tijiao():
name=cin_name.get()
if(1<=len(name)<=5):
l.config(text='成功使用该昵称,尝试与服务器连接中')
zjm(name)
else:
l.config(text='违规昵称,请重新输入')
cin_name.delete(0, END)
#取昵称环节
app=Tk()
app.title('在线聊天室')
app.geometry('500x300')
l=Label(app,text='输入您的昵称(1-5字符)')
l.pack()
cin_name=Entry(app,bd='2')
cin_name.pack()
tj=Button(app,text='提交',command=tijiao)
tj.pack()
app.mainloop()
服务端
import socket
import threading
import re
yh=[]
def getip(dree):
ip=re.findall("'.*'",str(dree))[0]
return ip
def fs(msg):
print('发送:',msg)
for i in yh:
try:
i.send(msg.encode('utf-8'))
except Exception as e:
pass
else:
pass
ck=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ck.bind(('192.168.19.74',7777))
ck.listen(1)
def cin():
while 1:
name='未命名用户'
try:
sed,dree=ck.accept()
print('有人连接上了服务器')
name=sed.recv(1024).decode('utf-8')#接受昵称
fs(name+' 加入群聊')
print(name+' 加入群聊')
yh.append(sed)
while 1:
date=sed.recv(1024).decode('utf-8')#接受数据
fs(name+':')#发送
fs(" "+date)
except:
pass
else:
pass
yh.remove(sed)
fs(name+' 退出群聊')
print(name+' 退出群聊')
if __name__ == "__main__":
for i in range(10):
t=threading.Thread(target=cin)
t.setDaemon(1)
t.start()
while 1:
if input()=='exit':
break
界面还是有点丑。。。