在其他WebSocket连接中发送WebSocket数据

nr7wwzry  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(146)

我们有一个loxone服务器,它通过loxone WebSocket(https://github.com/Loxone/lxcommunicator)将数据发送到我们的Web服务器。然后,该Web服务器将数据发送到客户端,也通过WebSocket。我们选择了这种设置,所以我们只有1个连接到loxone服务器本身,并且只需要进行一次身份验证。
现在的问题是,在连接loxone服务器之前,必须在config变量中声明从loxone服务器接收事件的函数。然而,在该作用域(socketOnEventReceived)中,我们没有连接到客户端的WebSocket。
我们也不能在loxone-socket定义周围添加client-websocket,因为这样会为每个客户端创建一个新的loxone-websocket连接。
这是我们当前的代码(ws/wss = client-socket,socket = loxone-socket)-这种方式的问题是它为每个接收到的事件创建一个新的WebSocket(显然也不可行)。

if (typeof LxCommunicator === 'undefined') {
    global.LxCommunicator = require('lxcommunicator');
}
//=== Node.js only ===
var fs = require('fs');
var WebSocket = require('ws');

var privateKey = ; //PkeyFile
var certificate = ; //CertFile

var credentials = { key: privateKey, cert: certificate };
var https = require('https');

var httpsServer = https.createServer(credentials);
httpsServer.listen(60088);

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
    server: httpsServer
});

// Prepare our variables
// uuid is used to identify a device
var uuid = getUUID(),
// delegateObj is contains all available delegate methods
delegateObj = {
    socketOnDataProgress: function socketOnDataProgress(socket, progress) {
        //console.log(progress);
    },
    socketOnTokenConfirmed: function socketOnTokenConfirmed(socket, response) {
        //console.log(response);
    },
    socketOnTokenReceived: function socketOnTokenReceived(socket, result) {
        //console.log(result);
    },
    socketOnTokenRefresh: function socketOnTokenRefresh(socket, newTkObj) {
        //console.log(newTkObj);
    },
    socketOnConnectionClosed: function socketOnConnectionClosed(socket, code) {
        process.exit(-1);
    },
    socketOnEventReceived: function socketOnEventReceived(socket, events, type) {
        events.forEach(function(event) {
            if(type === 2 || type ===3){ //2=lichtstatus 3=moodstatus
                var data = {};
                data["uuid"] = event.uuid;
                data["value"] = event.value;
                data['text'] = event.text;
                wss.on('connection', ws => {
                    ws.send(JSON.stringify(data));
                })
            }
        });
    }
},
// deviceInfo is a device specific information like the userAgent of a Browser
deviceInfo;

// Node.js doesn't have a userAgent, lets use the hostname instead
if (typeof window !== "undefined") {
    deviceInfo = window.navigator.userAgent;
} else {
    deviceInfo = require('os').hostname();
}
// OPTIONAL
// If no version is set LxCommunicator.WebSocket will fetch the version on its own
// This version is needed to determine if the Miniserver supports encryption and tokens
//LxCommunicator.setConfigVersion("9.3.2.20");

// Get the LxCommunicator.WebSocketConfig constructor, to save some space
var WebSocketConfig = LxCommunicator.WebSocketConfig;

// Instantiate a config object to pass it to the LxCommunicator.WebSocket later
var config = new WebSocketConfig(WebSocketConfig.protocol.WS, uuid, deviceInfo, WebSocketConfig.permission.APP, false);

// OPTIONAL: assign the delegateObj to be able to react on delegate calls
config.delegate = delegateObj;

// Instantiate the LxCommunicator.WebSocket, it is our actual WebSocket
var socket = new LxCommunicator.WebSocket(config);
// Open a Websocket connection to a miniserver by just providing the host, username and password!
socket.open("loxoneserver", "loxoneuser", "loxonepassword").then(function() {
    socket.send("jdev/sps/enablebinstatusupdate").then(function(respons) {
        console.log("Successfully executed '" + respons.LL.control + "' with code " + respons.LL.Code + " and value " + respons.LL.value);
    }, function(err) {
        console.error(err);
        process.exit(-1);
    });
}, function(e) {
    console.error(e);
});

字符串

wfveoks0

wfveoks01#

为所有连接保留一个索引,然后使用可用的连接。

let connections = {};
    wss.on('connection', ws => {
        //Keep an index for incoming connections
        const id = Math.random().toString(36).substr(2, 8); 
        connections[id] = ws;
        //remove once its closed.
        ws.on("close",()=>{
            delete connections[id]
        })
    })

字符串
然后像下面这样更新你的方法。

socketOnEventReceived: (socket, events, type) => {
        events.forEach(function(event) {
            if(type === 2 || type ===3){ //2=lichtstatus 3=moodstatus
                var data = {};
                data["uuid"] = event.uuid;
                data["value"] = event.value;
                data['text'] = event.text;

                Object.values(connections).forEach((conn)=>{
                    conn.send(JSON.stringify(data))
                })
                // wss.on('connection', ws => {
                //     ws.send(JSON.stringify(data));
                // })
            }
        });
    }


因为我不能在我这边运行你的代码。我不能说100%有效。

omhiaaxx

omhiaaxx2#

创建集中式数据存储并共享数据,以下三个选项

相关问题