Skip to content

Instantly share code, notes, and snippets.

@joshuajnoble
Last active March 3, 2017 10:19
Show Gist options
  • Save joshuajnoble/3439c57aa6f181c57450a0b445405ef1 to your computer and use it in GitHub Desktop.
Save joshuajnoble/3439c57aa6f181c57450a0b445405ef1 to your computer and use it in GitHub Desktop.
P5 to Processing
/* this is your node server, put it somewhere public
then call
npm install websockets --save
then node index.js
*/
var WebSocketServer = require('websocket').server;
var http = require('http');
var connections = [];
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets server
// we don't have to implement anything.
});
server.listen(8081, function() { });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
// This is the most important callback for us, we'll handle
// all messages from users here.
connection.on('message', function(message) {
// process WebSocket message
for( var i = 0; i < connections.length; i++ ){
if(connections[i] != this ) {
connections[i].send(JSON.stringify(message));
}
}
});
connection.on('close', function(connection) {
// close user connection
connections.splice(connections.indexOf(connection), 1);
});
connections.push(connection);
});
/*
Use https://github.com/alexandrainst/processing_websockets to create a websocket
*/
import websockets.*;
WebsocketClient wsc;
void setup(){
size(200,200);
String ipAddress = "";
wsc= new WebsocketClient(this, "ws://"+ipAddress+":8081");
}
void draw(){
}
void webSocketEvent(String msg){
println(msg);
}
void mousePressed(){
wsc.sendMessage("hi from processing");
}
var connection
function setup() {
createCanvas(500, 500);
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
connection = new WebSocket("ws://162.242.237.33:8081");
connection.onopen = function () {
// connection is opened and ready to use
};
connection.onerror = function (error) {
// an error occurred when sending/receiving data
};
connection.onmessage = function (message) {
// try to decode json (I assume that each message from server is json)
try {
var json = JSON.parse(message.data);
console.log(json['utf8Data']);
} catch (e) {
console.log(message.data);
return;
}
// handle incoming message
};
}
function mousePressed() {
connection.send("hi from p5");
}
function draw() {
background(0);
ellipse(width/2, height/2, size.x, size.y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment