iT邦幫忙

0

Nuxt 在使用webRTC時可以使用server send嗎

  • 分享至 

  • xImage

我有一個ws的modules檔案
程式碼如下

const WebSocket = require('ws')
const wss = new WebSocket.Server({ noServer: true })
var uuid = require('uuid');
const app = {
    locals: {
        connections: []
    }
}

wss.on('connection', ws => {
    const _connId = `conn-${uuid.v4()}`;
    app.locals.connections.push({ id: _connId });
    ws.send(JSON.stringify({ type: 'connection', id: _connId }))

    // send the list of connection ids
    broadcastConnections();
    ws.on('message', (message) => {
        ws.send(message);
        for (let i = 0; i < app.locals.connections.length; i++) {
            if (app.locals.connections[i] !== ws) {
                console.log('gogosendsignal');
            }
        }
    });

    ws.on('close', () => {
        let index = app.locals.connections.indexOf(ws);
        app.locals.connections.splice(index, 1);

        // send the list of connection ids
        broadcastConnections();
    });

    ws.on('error', error => {
        console.log('errrror', error);
    })

    function broadcastConnections() {
        let ids = app.locals.connections.map(c => c.id);
        app.locals.connections.forEach(c => {
            ws.send(JSON.stringify({ type: 'ids', ids }));
            //need use c.send(JSON.stringify({ type: 'ids', ids }));
        })
    }
})

export default function () {
    this.nuxt.hook('listen', server => {
        server.on('upgrade', (request, socket, head) => {
            wss.handleUpgrade(request, socket, head, ws => {
                wss.emit('connection', ws);
            })
        })
    })
}

當初是拿網路上的人寫的webRTC去改
app的部分對方是用

var express = require('express');
const app = express();

之後直接使用app.locals.connections
我在連線過程便發現我這樣擅自亂改是異想天開了XD
我不會送到正確的client端
但是我跟nuxt不熟的情況下也找不到有可以送的hook props
所以想上來請教各位大大 broadcastConnections function 裡面 server端的send該如何達成

非常感謝!!

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
mengke.me
iT邦新手 5 級 ‧ 2022-04-27 09:21:30
import WebSocket from 'ws';

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  const array = new Float32Array(5);

  for (var i = 0; i < array.length; ++i) {
    array[i] = i / 2;
  }

  ws.send(array);
});

https://www.npmjs.com/package/ws

我要發表回答

立即登入回答