前言
本来是为了局域网内能够复制段儿代码方便远程调试用的,ssh当然也可以,当然还是我头脑风暴散发,想到这里了。于是从网上拉了一个,改通之后,留一个备份。
期望还是很好的,以后用来支持ubuntu聊天之类的,当然这就得在html上来,不急慢慢来
代码
服务端代码:
import socket
import time
from threading import Thread
# 创建socket,绑定地址和端口号
host = '192.168.8.221'
port = 12345
# 创建套接字
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port)) # 绑定地址和端口号
# 存放用户昵称和地址
client = {}
address = {}
# 服务器可接收的client连接数
accept_num = 10
def client_join(conn, add): # 新客户端加入
print("为新用户建立进程")
nikename = conn.recv(1024).decode('utf8')
welcome = f'欢迎{nikename}加入聊天室'
print(welcome)
client[conn] = nikename # 将客户端加入client
brodcast(bytes(welcome, 'utf8')) # 广播欢迎信息
while True:
time.sleep(0.1)
try:
msg = conn.recv(1024)
print(msg)
brodcast(msg, nikename + ':') # 广播聊天信息
except:
print("接收失败")
conn.close()
client[conn]=None
brodcast(bytes(f'{nikename}离开聊天室\n', 'utf8')) # 用户断开连接
def brodcast(msg, nikename=''): # 向所有客户端广播新信息
for conn in client:
print(f"向{conn} 发送 {msg}")
conn.send(bytes(nikename, 'utf8') + msg)
print("发送成功")
if __name__ == '__main__':
s.listen(accept_num)
print('服务器已开启,正在监听用户请求')
while True:
conn, add = s.accept()
print(add, '已建立连接')
conn.send('欢迎来到聊天室,请输入你的昵称后进行聊天\n'.encode('utf8'))
address[conn] = add
Thread(target=client_join, args=(conn, add)).start() # 为新连接的客户端建立新线程
客户端代码:
import socket
import traceback
from threading import Thread
import tkinter as tk
# socket接入
host = '192.168.8.221'
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
def get_msg():
global text_message
while True:
try:
msg = s.recv(1024).decode('utf8')
print(f"得到了一些消息:{msg}")
text_message.insert(tk.END, msg) # 接收到广播信息时显示在消息窗口
except (BaseException, Exception) as e:
print(traceback.format_exc())
break
# 绘制GUI
app = tk.Tk()
app.title('多人聊天室')
# 消息窗口
message_frame = tk.Frame(width=480, height=300, bg='white') # 划分Frame
text_message = tk.Text(message_frame)
message_frame.grid(row=0, column=0, padx=3, pady=6) # 0行0列,边框距离x=3px,y=6px
message_frame.grid_propagate(0) # 固定面板大小
text_message.grid()
# 输入窗口
text_frame = tk.Frame(width=480, height=100)
text_text = tk.Text(text_frame)
text_frame.grid(row=1, column=0, padx=3, pady=6)
text_frame.grid_propagate(0)
text_text.grid()
# 发送按钮
def send():
send_msg = text_text.get('0.0', tk.END) # 获取输入窗口文本内容
# print(send_msg)
s.send(send_msg.encode())
text_text.delete('0.0', tk.END) # 清空输入窗口文本内容
receive_thread = Thread(target=get_msg) # 开启线程用于接收广播信息
receive_thread.start()
print('连接服务器成功')
send_frame = tk.Frame(width=480, height=30)
button_send = tk.Button(send_frame, text='发送', command=send) # 添加按钮并绑定发送功能
send_frame.grid(row=2, column=0, padx=10, sticky='E') # 2行0列,右对齐,距离边框10px
# send_frame.grid_propagate(0)
button_send.grid()
app.mainloop()
最后我也是复制粘贴修改的,也支持下原创:Python实战 | socket+thinter 实现多人聊天室_socket实现多人聊天室图片-CSDN博客