代码之家  ›  专栏  ›  技术社区  ›  Jack D

从Python到Nuxt 3客户端的WebSocket

  •  0
  • Jack D  · 技术社区  · 2 年前

    我正试图从以下位置创建websocket连接 python.py index.vue .


    我无法在页面加载时建立连接。


    索引.vue->model.post.ts->python.py-> (websocket) ->index.vue


    我想从发送数据 python.py 而在过程中 index.vue 客户端提供实时更新,这就是我遇到的问题。


    参考YouTube视频 https://www.youtube.com/watch?v=d-LSN-xo6N4
    引用GitHub https://github.com/adityar15/nuxt3socket/tree/master


    "@types/uuid": "^9.0.4",
    "@types/ws": "^8.5.6"
    

    /index.vue

    <div>message: {{ message }}</div>
    
    
    import { v4 as uuid } from "uuid";
    
    const uid = uuid()
    const message = ref<string>("")
    const { $socket } = useNuxtApp()
    
    onMounted(() => {
        $socket.onopen = () => {
            console.log('WebSocket is open now.')
            localStorage.setItem(`connection-${uid}`, uid)
            $socket.send(uid)
        }
    
        // $socket.onmessage = ({ data }: any) => {
        //     console.log("data:", data)
        //     message.value = data
        // }
    
        $socket.onclose = function () {
            console.log("disconnected")
        }
    


    /插件/webocket.client.ts

    export default defineNuxtPlugin(() => {
      if (process.server) return
    
      const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:"
      let socket = new WebSocket(`${wsProtocol}//${window.location.host}`)
      
      return {
        provide: {
          socket,
        },
      }
    })
    


    /服务器/中间件/socket.ts

    import WebSocket, { WebSocketServer } from "ws"
    
    type Client = {
      id: string
      send: (message: string) => void
      readyState: number
    }
    
    declare global {
      var wss: WebSocketServer
      //var clients: Client[]
    }
    
    let wss: WebSocketServer
    //let clients: Client[] = []
    
    export default defineEventHandler((event) => {
    
      if (!global.wss) {
        wss = new WebSocketServer({ server: (event.node.res.socket as any)?.server })
        wss.on("connection", function (socket) {
          console.log('New connection established.')
    
          socket.send("connected")
    
          socket.on("error", function (error) {
            console.log(`Socket Error: ${error}`);
          });
    
        wss.on("error", function (error) {
          console.log(`WebSocket Server Error: ${error}`);
        });
    
        global.wss = wss
      }
    })
    


    data.py

    pip install websocket-client

    from websocket import create_connection
    
    ws_url = 'ws://localhost:3000'
    print(f"Attempting to connect to {ws_url}")
    ws = create_connection(ws_url)
    print("WebSocket connection established.")
    
    def send_progress_data(data):
        print('sending progress data...')
        message = f"data: {data}" 
        ws.send(message)
        print(f"Sent: {message}")
    
    ...
    

    我没有收到任何错误消息,但没有建立连接

    0 回复  |  直到 2 年前
    推荐文章