Moon Ha

performer-composer / researcher

UDP-to-WebSocket Communication and p5.js

This guide is written for macOS but should be easy to adapt for other operating systems.

Receiving UDP Data

You need to install Node.js:
brew install node

Then, Navigate to your project directory and initialize a new Node.js project:

npm init -y

You need the dgram and ws packages. Install them using npm:

npm install dgram ws

Create a UDP and WebSocket server. Save the following code in a file named udp_websocket_server.js:

const dgram = require('dgram');
const WebSocket = require('ws');

// UDP Server Setup
const udpServer = dgram.createSocket('udp4');
const udpPort = 41234; // UDP port for receiving data

// WebSocket Server Setup
const wss = new WebSocket.Server({ port: 8080 }); // WebSocket port

// Handle incoming UDP messages
udpServer.on('message', (msg) => {
  console.log(`Received UDP message: ${msg}`);
  // Forward UDP message to all WebSocket clients
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(msg.toString());
    }
  });
});

// Handle WebSocket connections
wss.on('connection', (ws) => {
  console.log('WebSocket client connected');

  ws.on('close', () => {
    console.log('WebSocket client disconnected');
  });
});

// Start UDP server
udpServer.bind(udpPort, () => {
  console.log(`UDP server listening on port ${udpPort}`);
});

Create a file named sketch.js:

let socket;
let receivedData = '';

function setup() {
  createCanvas(windowWidth, windowHeight);
  
  // Connect to WebSocket server
  socket = new WebSocket('ws://localhost:8080');
  
  // Handle incoming messages from WebSocket server
  socket.onmessage = function(event) {
    receivedData = event.data; // Store the received data
  };
}

function draw() {
  background(200);
  
  // Use the received data in your sketch
  fill(0);
  textSize(32);
  textAlign(CENTER, CENTER);
  text(receivedData, width / 2, height / 2);
}

In your terminal, run the Node.js server:
node udp_websocket_server.js

Ensure that you set the correct IP address and port number. You should be able to see data in both the web browser and the terminal.

Posted in

Reply

Your email address will not be published. Required fields are marked *