Dette eksempel viser hvordan man kan lave en webserver, der kan køre et eksempel hvor clienter på forskellige maskiner kan kommunikere via en web-socket.
Det er baseret på en videotutorial af Daniel Shiffman fra The Coding Train.
constexpress=require('express');
constapp=express();
constport=process.env.PORT||3000;
// Set up the server
// process.env.PORT is related to deploying on heroku
constserver=app.listen(port);
app.use(express.static(__dirname+'/public'));
console.log(`Server is running on http://localhost:${port}`);
constsocket=require('socket.io');
constio=socket(server);
io.sockets.on('connection', newConnection);
functionnewConnection(socket) {
console.log(`New connection ${socket.id}`);
socket.on('mouse', mouseMsg);
functionmouseMsg(data) {
socket.broadcast.emit('mouse', data);
// NB! send to all listeners (including source of incomming event)
// io.emit('some event, theDataToSend)
console.log(data);
}
}
public/sketch.js
constsocket=io();
functionsetup() {
createCanvas(400, 400);
background(0);
// Set up listener for incomming socket events
socket.on('mouse', newDrawing);
}
constlineWidth=10;
functionnewDrawing(data) {
// Draw some white circles with different colors
colorMode(RGB, 255);
fill(255, 0, 100);
noStroke();
ellipse(data.x, data.y, lineWidth, lineWidth);
}
functionmouseDragged() {
letcurrentNumX=mouseX;
letlowerBound=0;
letupperBoundX=width; //100;
letnormalizedX=norm(currentNumX, lowerBound, upperBoundX);
letcurrentNumY=mouseY;
letupperBoundY=height; //100;
letnormalizedY=norm(currentNumY, lowerBound, upperBoundY);
colorMode(HSB, 255);
letc=color(normalizedX*255, normalizedY*255, 255);
// Draw some white circles
fill(255);
noStroke();
ellipse(mouseX, mouseY, lineWidth, lineWidth);
constdata= {
x:mouseX,
y:mouseY,
};
console.log(`Sending ${data.x}${data.y} `);
socket.emit("mouse", data);
}