104 lines
3.0 KiB
JavaScript
104 lines
3.0 KiB
JavaScript
let hostConnection;
|
|
let displayConnection;
|
|
|
|
function initHostConnection() {
|
|
console.log("Initialize Host connection...");
|
|
|
|
hostConnection.on('message', (data) => {
|
|
console.log("[HOST] " + data);
|
|
if (displayConnection) {
|
|
displayConnection.send("" + data);
|
|
}
|
|
});
|
|
|
|
hostConnection.on('error', (data) => {
|
|
console.error("[HOST] " + data);
|
|
hostConnection = undefined;
|
|
if (displayConnection) {
|
|
displayConnection.send("HOST-DISCONNECTED");
|
|
}
|
|
});
|
|
|
|
hostConnection.on('close', (code, reason) => {
|
|
console.error("[HOST] " + code + " " + reason);
|
|
hostConnection = undefined;
|
|
if (displayConnection) {
|
|
displayConnection.send("HOST-DISCONNECTED");
|
|
}
|
|
});
|
|
|
|
hostConnection.send("HOST");
|
|
if (displayConnection) {
|
|
displayConnection.send("HOST-CONNECTED");
|
|
hostConnection.send("DISPLAY-CONNECTED");
|
|
}
|
|
}
|
|
|
|
function initDisplayConnection() {
|
|
console.log("Initialize Display connection...");
|
|
|
|
displayConnection.on('message', (data) => {
|
|
console.log("[DISPLAY] " + data);
|
|
});
|
|
|
|
displayConnection.on('error', (data) => {
|
|
console.error("[DISPLAY] " + data);
|
|
displayConnection = undefined;
|
|
if (hostConnection) {
|
|
hostConnection.send("DISPLAY-DISCONNECTED");
|
|
}
|
|
});
|
|
|
|
displayConnection.on('close', (code, reason) => {
|
|
console.error("[DISPLAY] " + code + " " + reason);
|
|
displayConnection = undefined;
|
|
if (hostConnection) {
|
|
hostConnection.send("DISPLAY-DISCONNECTED");
|
|
}
|
|
});
|
|
|
|
displayConnection.send("DISPLAY");
|
|
if (hostConnection) {
|
|
hostConnection.send("DISPLAY-CONNECTED");
|
|
displayConnection.send("HOST-CONNECTED");
|
|
}
|
|
}
|
|
|
|
export function initWebsocket(app) {
|
|
app.ws("/websocket", (ws, req) => {
|
|
console.log("Trying to connect");
|
|
ws.on('error', console.error);
|
|
|
|
ws.on('message', (data) => {
|
|
if (ws == hostConnection || ws == displayConnection) return;
|
|
console.log('received: %s', data);
|
|
if (data == "HOST") {
|
|
if (hostConnection === undefined) {
|
|
hostConnection = ws;
|
|
initHostConnection();
|
|
}
|
|
else
|
|
{
|
|
ws.send("ERROR HOST");
|
|
ws.close();
|
|
}
|
|
} else if (data == "DISPLAY") {
|
|
if (displayConnection === undefined) {
|
|
displayConnection = ws;
|
|
initDisplayConnection();
|
|
}
|
|
else
|
|
{
|
|
ws.send("ERROR DISPLAY");
|
|
ws.close();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ws.send("ERROR MESSAGE");
|
|
ws.close();
|
|
}
|
|
})
|
|
});
|
|
}
|