首页 > 解决方案 > 根据服务器动态改变 websocket URL

问题描述

有人尝试过使用 WebSocket 吗?如何在部署时动态更改我的 WebSocket URL?我WS在服务器端使用 npm 和 node 和 express。

这是我使用 WebSocket html5 API 的 WebSocket 客户端代码。

我的 WebSocket 网址当前位于本地主机上。这肯定不适用于部署。

const socket = new WebSocket(`ws://localhost:8080/${userID}`);

socket.onopen = function() {
  // ! from local storage or cookies get the user information
  console.log('open client');
};

socket.onmessage = function(event) {
  console.log(event);
};

socket.onclose = function() {
  console.log('client close');
};

这是WSnpm 包的代码。

const WebSocket = require('ws');

const wss = new WebSocket.Server({
  port: 8080,
});

const clientsId = {}; // ! client ids

wss.on('connection', (ws, req) => {
  // ! gets the parameters of the url
  const param = req.url;

  // ! parse the url to removed /
  const userId = param
    .split('')
    .slice(1, param.split('').length)
    .join('');

  // ! take the userId making it as a key
  // ! then the current socket connection will be the users value
  clientsId[userId] = ws;

  // ! every message will invoke this function
  // ! the incoming message are stringfy need to parse
  ws.on('message', (incomingMsg) => {
    // ! parsing the incoming msg
    incomingMsg = JSON.parse(incomingMsg);
    // ! from the incoming msg get the paired ID
    const clientPairedId = incomingMsg.pairId;
    // ! gets the socket connection from the clientsId object using the paired Id from incoming msg
    const socketPerClient = clientsId[clientPairedId];
    // ! if socketPerClient in not null
    if (socketPerClient) {
      // ! using the value from socketPerClient get the send method and use it to send the data
      socketPerClient.send(
        JSON.stringify({
          name: incomingMsg.userID,
          msg: incomingMsg.msg,
          senderId: incomingMsg.senderId,
        })
      );
      return;
    }
  });

  ws.on('close', function close() {
    console.log('disconnected server', ws.readyState);
  });
});

module.exports = wss;

请。帮助。非常感谢您。

标签: urldynamicwebsocketserver

解决方案


推荐阅读