根据服务器动态更改Websocket URL

时间:2018-10-05 21:58:40

标签: url dynamic websocket server

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

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

我的WebSocket URL当前在本地主机上。这肯定无法在部署中起作用。

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');
};

这是WS npm软件包的代码。

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;

请。救命。非常感谢。

0 个答案:

没有答案
相关问题