fleshing out a bit

This commit is contained in:
2023-11-22 15:37:36 +01:00
parent 8195511332
commit ea0c7f3165

View File

@ -1,48 +1,51 @@
export let socket = new WebSocket('ws://localhost:3000') export let socket = new WebSocket("ws://localhost:3000");
export interface OSCMessage { export interface OSCMessage {
address: string address: string;
message: object port: number;
timetag: number message: object;
timetag: number;
} }
// @ts-ignore // @ts-ignore
socket.onopen = function(event) { socket.onopen = function (event) {
console.log("Connected to WebSocket Server") console.log("Connected to WebSocket Server");
// Send an OSC-like message // Send an OSC-like message
socket.send(JSON.stringify({ socket.send(
address: '/test', JSON.stringify({
args: [1, 2, 3] address: "/connected",
})) args: [1],
})
);
socket.onerror = function(error) { socket.onerror = function (error) {
console.log("Websocket Error:", 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) { 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) { if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message)); socket.send(JSON.stringify(message));
} else { } else {
// Reconnect if the WebSocket is not open console.log("WebSocket is not open. Attempting to reconnect...");
console.log('WebSocket is not open. Attempting to reconnect...'); if (
// Close the existing socket if necessary socket.readyState === WebSocket.CONNECTING ||
if (socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN) { socket.readyState === WebSocket.OPEN
) {
socket.close(); socket.close();
} }
// Create a new WebSocket connection // 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 // Send the message once the socket is open
socket.onopen = () => { socket.onopen = () => {