import tkinter as tk
import socket
import threading
# 创建socket对象
server_socket = socket.socket()
# 设置默认主机和端口号
HOST = '127.0.0.1'
PORT = 8888
# 监听客户端连接的线程
def handle_client_connection():
while True:
# 等待客户端连接
client_socket, address = server_socket.accept()
# 打印客户端连接成功消息
text_box.insert(tk.END, f'\nclient connected...\n')
# 启动新线程处理客户端请求
client_thread = threading.Thread(target=handle_client_request, args=(client_socket,))
client_thread.start()
# 处理客户端请求的函数
def handle_client_request(client_socket):
while True:
# 接收客户端发送的数据
data = client_socket.recv(1024).decode()
if not data:
break
# 显示客户端发送的数据
text_box.insert(tk.END, f'{data}\n')
# 将数据发送回客户端
client_socket.sendall(data.encode())
client_socket.close()
# 客户端连接按钮的事件处理函数
def connect_to_server():
# 连接服务器
server_socket.connect((HOST, PORT))
# 向文本框中插入“client connected...”消息
text_box.insert(tk.END, f'\nclient connected...\n')
# 创建应用程序窗口
app = tk.Tk()
app.title('Socket Server')
# 创建多行文本框
text_box = tk.Text(app, height=10, width=50)
text_box.pack()
# 创建连接按钮
connect_button = tk.Button(app, text='Connect', command=connect_to_server)
connect_button.pack()
# 启动服务器
server_socket.bind((HOST, PORT))
server_socket.listen(5)
# 向文本框中插入“server starting...”消息
text_box.insert(tk.end, "server starting...")