From ea0c7f31650727b65849a2e4710b0bb1af5bdc31 Mon Sep 17 00:00:00 2001 From: Raphael Forment Date: Wed, 22 Nov 2023 15:37:36 +0100 Subject: [PATCH] fleshing out a bit --- src/IO/OSC.ts | 59 +++++++++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/src/IO/OSC.ts b/src/IO/OSC.ts index 39c6816..9f8e429 100644 --- a/src/IO/OSC.ts +++ b/src/IO/OSC.ts @@ -1,48 +1,51 @@ -export let socket = new WebSocket('ws://localhost:3000') +export let socket = new WebSocket("ws://localhost:3000"); export interface OSCMessage { - address: string - message: object - timetag: number + address: string; + port: number; + message: object; + timetag: number; } // @ts-ignore -socket.onopen = function(event) { - console.log("Connected to WebSocket Server") +socket.onopen = function (event) { + console.log("Connected to WebSocket Server"); // Send an OSC-like message - socket.send(JSON.stringify({ - address: '/test', - args: [1, 2, 3] - })) + socket.send( + JSON.stringify({ + address: "/connected", + args: [1], + }) + ); - socket.onerror = function(error) { + socket.onerror = function (error) { console.log("Websocket Error:", error); - } - - socket.onmessage = function(event) { - console.log("Received: ", event.data) - } -} - - -// export function sendToServer(message: OSCMessage) { -// socket.send(JSON.stringify(message)); -// } + }; + socket.onmessage = function (event) { + console.log("Received: ", event.data); + }; +}; export function sendToServer(message: OSCMessage) { - // Check if the WebSocket is open + // Check the port in the message and change port if necessary + if (message.port != parseInt(socket.url.split(":")[2])) { + socket.close(); + socket = new WebSocket(`ws://localhost:${message.port}`); + } + if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify(message)); } else { - // Reconnect if the WebSocket is not open - console.log('WebSocket is not open. Attempting to reconnect...'); - // Close the existing socket if necessary - if (socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN) { + console.log("WebSocket is not open. Attempting to reconnect..."); + if ( + socket.readyState === WebSocket.CONNECTING || + socket.readyState === WebSocket.OPEN + ) { socket.close(); } // Create a new WebSocket connection - socket = new WebSocket('ws://localhost:3000'); + socket = new WebSocket("ws://localhost:3000"); // Send the message once the socket is open socket.onopen = () => {