url - 根据服务器动态改变 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');
};
这是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;
请。帮助。非常感谢您。
解决方案
推荐阅读
- scala - org.http4s.client 带有标题和 UriForm 的帖子
- terraform - Terraform:为输出指定特定的 Docker 网络名称
- javascript - 如何在条纹支付表单上禁用 jquery 中的验证
- arrays - 如何打印二维数组?
- node.js - 使用 MongoDB 驱动程序 3.6 在 Node.js 中运行查询的最佳实践?
- c - GtkTextView 文本着色未按预期工作
- python - 如何根据二进制视频帧中的近似形状过滤轮廓
- reactjs - 使用 Multiple Switch 在 reactjs 中提供 Blanc 组件
- python-3.x - Pydbus 更多通知同时处理
- reactjs - 如何保护 ASP.NET Core Web API 端点只允许来自 React 应用程序的请求?