Python利用套接字(socket)写的联机测试
  • 板块学术版
  • 楼主Fish_redflying
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/3/1 21:10
  • 上次更新2024/3/1 23:09:23
查看原帖
Python利用套接字(socket)写的联机测试
1029122
Fish_redflying楼主2024/3/1 21:10

窗口一直未响应

客户端

import socket
from tkinter import simpledialog
from tkinter import *

root=Tk()

SERVER_HOST = socket.gethostname()
SERVER_PORT = 8000
BUFFER_SIZE = 1024
username=simpledialog.askstring("Ask","你的名字")


show=Canvas(root,height=300,width=300)
users={}
shows={}

userspos=[150,150,150,150]

def handle_input(client_socket):
    while True:
        root.update_idletasks()
        msg = username+"/"+" ".join(map(str,userspos))
        client_socket.send(msg.encode())
        if msg == 'quit':
            break

def handle_output(client_socket):
    while True:
        root.update_idletasks()
        msg = client_socket.recv(BUFFER_SIZE).decode()
        if msg== 'quit':
            break
        msg=msg.split("|")
        for i in msg :
            name,pos=i.split("/")
            users[name]=list(map(pos.split(" ")))
        for i in users.keys() :
            if not i in shows :
                shows[i]=show.create_oval(users[i][0]-20,users[i][1]-20,users[i][2]+20,users[i][2]+20,fill="red")
            shows[i].coord(shows[i],users[i][0]-20,users[i][1]-20,users[i][2]+20,users[i][2]+20)

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_HOST, SERVER_PORT))
root.after(0,lambda :handle_output(client_socket,))

root.after(0,lambda :handle_input(client_socket,))

root.mainloop()


import socket
import threading

SERVER_HOST = socket.gethostname()
SERVER_PORT = 8000
BUFFER_SIZE = 1024

users_data={}

def handle_client(client_socket):
    """处理客户端连接"""

    while True:
        msg = client_socket.recv(BUFFER_SIZE)
        broadcast(msg.decode())
def broadcast(msg):
    """向所有已连接的客户端广播消息"""
    name,pos=msg.split("/")
    users_data[name]=pos
    print(name,"join")
    change=[]
    for i in users_data.keys() :
        change.append(i+"/"+users_data[i]+"|")
    for client in clients:
        client.send(" ".join(change).encode())

if __name__ == '__main__':
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((SERVER_HOST, SERVER_PORT))
    server_socket.listen(5)
    print(f'[*] 正在听取端口 {SERVER_PORT}')

    clients = []

    while True:
        client_socket, addr = server_socket.accept()
        clients.append(client_socket)

        # 开启线程
        thread = threading.Thread(target=handle_client, args=(client_socket,))
        thread.start()
2024/3/1 21:10
加载中...