Skip to content

Instantly share code, notes, and snippets.

@philippbosch
Last active December 16, 2015 01:29
Show Gist options
  • Save philippbosch/5355248 to your computer and use it in GitHub Desktop.
Save philippbosch/5355248 to your computer and use it in GitHub Desktop.
Connection from a web app to a Processing sketch through websockets
<script>
// Create a connection to the server
var ws = new WebSocket('ws://172.18.246.234:8080/p5websocket');
// As soon as the connection is established, send a "Ping" message to the server
ws.onopen = function() {
ws.send('Ping');
};
// Whenever we receive a message from the server, display it in a popup
ws.onmessage = function(e) {
alert(e.data);
};
</script>
WebSocketP5 socket;
void setup() {
// Setup the socket that listens for incoming connections
socket = new WebSocketP5(this, 8080);
}
void draw() {
}
void stop() {
// When the processing sketch stops, kill the server
socket.stop();
}
void websocketOnMessage(WebSocketConnection con, String msg) {
// Whenever we receive a message from one of the phones, this code will be executed
println(msg);
}
void mousePressed() {
// Send a "Pong" message to all connected phones
socket.broadcast("Pong");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment