首页 > 解决方案 > 如何使用访问令牌连接到翼龙 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}`);
});

标签: javascriptnode.jswebsocketpanelaccess-token

解决方案


推荐阅读