Simple example of getting Websockets broadcast data into Max?

seejayjames's icon

Tearing my hair out here...

I have a standalone node.js server accepting incoming GET requests from web apps (just simple UIs for now, sliders, buttons, etc). Works great and I've gotten it to broadcast to p5.js and Unity via Websockets.

I've tried everything I can think of in Max but no luck. Don't want to use MXJ because I'll need to change how the server sends data (correct?) -- also don't want to rely on Java being installed on a target computer.

I get this error when I do "script start" in the Max Console (5 times):

node.script: Node child process quit, will restart

I also get 6 pairs of

Client connected
Client disconnected

in my node.js console.

Anybody seen this? Anyone have a super-simple setup that works? Thanks!

Tried to attach files but it's not allowed. Below is the js code inside Max:

// Max WebSocket Client Script to receive data
const WebSocket = require('ws');
// Replace 'ws://localhost:3000' with your Node.js WebSocket server address
const ws = new WebSocket('ws://localhost:3000');
// When connection opens
ws.on('open', () => {
  post('Connected to Node.js server\n');
});
// When data is received from Node.js
ws.on('message', (data) => {
  post('Received from Node.js: ' + data + '\n');
  outlet(0, data); // Send data to Max/MSP patch
});
// Handle connection errors
ws.on('error', (error) => {
  post('WebSocket error: ' + error + '\n');
});
// When connection closes
ws.on('close', () => {
  post('Disconnected from Node.js server\n');
});
seejayjames's icon

Sorry if the code formatting is wonky...

The maxpat is dirt simple, no need to attach. I can put the node server code if needed.

Andrew Benson's icon

I haven't looked at your setup yet, but I can recommend this Node Recipe article I put together after the Max 8 release, which uses Socket.IO, but using ws should be pretty similar in terms of setup.

seejayjames's icon

This looks great, thank you so much!

I might use this version and see about modifying the other code to use Socket IO instead, could be easier than trying to create a ws setup in Max, not sure.

Am hoping to put together an easy-to-use package with some webpage UI templates and all the parts needed for communication from mobile devices to Max and/or any other program that supports sockets/ws/etc. I'd like the same protocol for everything for simplicity. Will report back, thanks again!