最近学习了一下socket套接字,略有心得,想着做一个简单聊天室加深学习,代码如下:
服务端:
import socket
import threading
import time
def main():
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创造服务器server
server.bind(("",8000))#绑定创造的服务器server和端口
server.listen(5)#监听客户端连接请求
clients = []#存放连接客户端
print(" **聊天室服务器 ")
def receive_user():
while True:
global address
client,address = server.accept()#接收客户端请求
client.send(("欢迎来到聊天室"+"\n").encode("utf-8"))#发送欢迎信息
clients.append(client)#存放连接用户信息
thread_receive_msg = threading.Thread(target=receive_msg,args =(client,))
thread_receive_msg.start()
def receive_msg(client):
while True:
time.sleep(1)
try:
if client in clients:
receive_data = client.recv(1024).decode("utf-8")#获取客户端接受信息
print(receive_data)
for cli in clients:
cli.send(receive_data.encode("utf-8"))#转发接受客户端信息
except BaseException as error:
print("Error",error)
clients.remove(client)
#客户端中断请求
def total_clients():
while True:
print("当前在线人数%s"%(len(clients)))
for cli in clients:
print("当前在线客户端地址:{}".format(address))#打印客户端地址
time.sleep(3)
#监视当前在线人数
thread_receive_user = threading.Thread(target=receive_user)
thread_total_clients = threading.Thread(target = total_clients)
thread_receive_user.start()
thread_total_clients.start()
thread_total_clients.join()
if __name__ == "__main__":
main()
客户端:
import socket
import threading
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import tkinter as tk
def main():
root = Tk()#创造窗口对象
root.title("**网络聊天室")#标题
w = root.winfo_screenwidth()#获取屏幕宽度
h = root.winfo_screenheight()#获取屏幕高度
width = 410
height = 345
pw = (w - width - 110)/2
ph = (h - height - 140)/2
root.geometry("%dx%d+%d+%d"%(width,height,pw,ph))#设置窗口长度和宽度
try:
guest = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
guest.connect(("#这里是服务器的ip地址",8000))#建立客户端连接
def receive():
try:
while True:
receive_data = (guest.recv(1024).decode("utf-8"))#接受服务器消息
聊天区.configure(state = "normal")
聊天区.insert(END,receive_data)
聊天区.see(END)
聊天区.configure(state = "disabled")
except Exception as error:
tk.messagebox.showinfo("Error",error)
root.destroy()
def send_msg():
def send():
try:
msg = "*guest: "+发送区.get("0.0",END)
guest.send(msg.encode("utf-8"))#发送消息
发送区.delete(1.0,END)#清空发送区内容
except Exception as error:
tk.messagebox.showinfo("Error",error)
root.destroy()
thread2 = threading.Thread(target = send)
thread2.start()
#开启发送线程
聊天室 = Label(root,text = "聊天区",font = ("微软雅黑",18))
聊天室.place(x = 145,y = 10)
聊天区 = Text(root,relief = RAISED,font = ("微软雅黑",10))
聊天区.configure(state = "disabled")
聊天区.place(x = 50,y = 50,width = 280,height = 150)
聊天区滚动条 = Scrollbar()
聊天区滚动条.config(command = 聊天区.yview)
聊天区.config(yscrollcommand = 聊天区滚动条.set)
聊天区滚动条.place(x = 330,y = 50,width = 20,height = 150)
发送框 = Label(root,text = "发送区",font = ("微软雅黑",15))
发送框.place(x = 152,y = 210)
发送区 = Text(root,font = ("微软雅黑",9))
发送区.place(x = 113,y = 250,width = 150,height = 70)
发送区滚动条 = Scrollbar()
发送区滚动条.config(command = 发送区.yview)
发送区.config(yscrollcommand = 发送区滚动条.set)
发送区滚动条.place(x = 263,y = 250,width = 20,height = 70)
发送消息 = ttk.Button(root,text = "发送",command = send_msg)
发送消息.place(x = 300,y = 240,width = 55,height = 32)
##tk组件设置
thread1 = threading.Thread(target = receive)
thread1.start()
#开启接受消息线程
except Exception as error:
tk.messagebox.showinfo("Error",error)
root.destroy()
root.mainloop()
if __name__ == "__main__":
main()
效果如下:
这里还有几个问题没有解决,如该代码在同一台电脑可运行,当进行两台电脑连接时,会出现TimeoutError: [WinError 10060]报错,我查阅网上资料,尝试了关闭防火墙等操作,却依然失败,还请大佬们指教.