websocket 初级

- npm install websocket

- App.vue

// App.vue





- src/websocket.js

//默认使用
export default class WebSocketService {
    constructor(url) {
        this.url = url;
        this.websocket = null;
    }

    connect() {
        this.websocket = new WebSocket(this.url);

        this.websocket.onopen = () => {
            console.log("WebSocket 连接成功");
            // 可选:在 WebSocket 连接成功时执行一些操作
        };

        this.websocket.onclose = () => {
            console.log("WebSocket 连接关闭");
            // 可选:在 WebSocket 连接关闭时执行一些操作
        };

        this.websocket.onerror = (error) => {
            console.error("WebSocket 出错:", error);
        };
    }

    send(message) {
        if (this.websocket) {
            this.websocket.send(JSON.stringify(message));
        } else {
            console.error("WebSocket 未连接.");
        }
    }

    close() {
        if (this.websocket) {
            this.websocket.close();
        }
    }

    // 根据需要添加更多方法,例如处理接收到的消息
}

- 启动服务

import asyncio
import websockets


async def server(websocket, path):
    print(f"客户端 {websocket.remote_address} 连接成功")

    try:
        count = 0
        while True:
            message = await websocket.recv()
            print(f"接收到消息:{message}")
            count += 1
            await websocket.send(message + str(count))
            print(f"发送消息:{message}")
    except websockets.ConnectionClosed:
        print(f"客户端 {websocket.remote_address} 断开连接")


start_server = websockets.serve(server, "localhost", 12345)

asyncio.get_event_loop().run_until_complete(start_server)
print("WebSocket 服务器已启动,等待连接...")

try:
    asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
    print("\nWebSocket 服务器已关闭")

你可能感兴趣的:(websocket,网络协议,网络)