javascript - 如何使用访问令牌连接到翼龙 WebSocket
问题描述
如何使用 Node.js 的 websocket 包装器库 - websocket 连接到翼龙的 websocket 服务器以获取翼龙内的服务器终端。通过使用帐户 API 密钥获取访问令牌,我已经完成了一半,但我无法使用该令牌进行连接。
到目前为止,这是我的代码,请随时编辑它:
var fetch = require("node-fetch");
var WebSocketClient = require("websocket").client;
var config = class {
static panelUrl = "http://*************.icedev.tk";
static pterodactylUserApiKey = "********************************************FnTI";
};
// Get a websocket access token
fetch(`${config.panelUrl}/api/client/servers/5f1ad850/websocket`, {
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${config.pterodactylUserApiKey}`
}
}).then(res => res.json())
.then((json) => {
// Assign gvariables to the tokens
const token = json.data.token,
socket = json.data.socket;
var client = new WebSocketClient();
// Websocket Events
client.on("connectFailed", function(error) {
console.log("Connect Error: " + error.toString());
});
client.on("connect", function(connection) {
console.log("WebSocket Client Connected");
connection.on("error", function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on("close", function() {
console.log("echo-protocol Connection Closed");
});
connection.on("message", function(message) {
if (message.type === "utf8") {
console.log("Received: '" + message.utf8Data + "'");
}
});
});
// connect to the socket
client.connect(`${socket}`, ["Sec-WebSocket-Protocol"], "*", `Authorization: Bearer ${token}`);
});
解决方案
推荐阅读
- django - 502 Bad Gateway nginx 服务器
- c# - 如何将进度消息异步发送到 WPF UI
- webdrivermanager-java - webdrivermanager - 关闭或重新配置控制台日志记录
- jupyter-notebook - 如何在 VS-Code 中输入 Jupyter 风格的代码对齐行为?
- linux - 如何在 Linux/Systemd/Networkd 上启动时启用 VRF
- javascript - 当我使用节点服务器时,我的 css、js 和图像停止工作
- c++ - C++ bool 得到随机/错误的值?
- python-3.x - 更改列表副本的函数
- sympy - 如何打印 sympy 矩阵....为什么要换行?
- junit - 使用 mockito 进行 WebClient GET 单元测试