Socket IO

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.

Socket io video tutorial

12.1: Introduction to Node - WebSockets and p5.js Tutorial

  • Introduktion til web sockets.
  • Installation af node
  • “hello world” demo

12.2: Using Express with Node - WebSockets and p5.js Tutorial

  • Hosting af statiske klient filer på node server med Express.

12.3: Connecting Client to Server with Socket.io - WebSockets and p5.js Tutorial

  • Tilføjelse af Socket.io til klient og server
  • Vis klientens ID når de forbinder sig

12.4: Shared Drawing Canvas - WebSockets and p5.js Tutorial

  • Afsendelse af hændelser (events) fra klienter
  • Broadcast af events fra server
  • Tegning på skærmen i de modtagende klienter

Materiale

Kode eksempel

Det kan være nødvendigt med et par små justeringer ift. koden i videoerne.

Her følger indholdet af mine filer

Indholdet i package.json.

{
  "name": "socket-io-demo",
  "version": "1.0.0",
  "description": "Socket io demo with p5js",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Getsrevel",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "socket.io": "^2.3.0"
  }
}

Bemærk at socket-io klienten hentes fra den lokale server i filen public/index.html, som beskrevet i socket.io - Get started.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Socket io demo</title>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
    <script type="text/javascript" src="sketch.js"></script>
    <style>
      body {
        padding: 20px;
      }
    </style>
</head>
<body>
    <h1>Socket demo</h1>
</body>
</html>
server.js
const express = require('express');

const app = express();

const port = process.env.PORT || 3000;

// Set up the server
// process.env.PORT is related to deploying on heroku
const server = app.listen(port);
app.use(express.static(__dirname +'/public'));
console.log(`Server is running on http://localhost:${port}`);


const socket = require('socket.io');
const io = socket(server);

io.sockets.on('connection', newConnection);

function newConnection(socket) {
    console.log(`New connection ${socket.id}`);

    socket.on('mouse', mouseMsg);

    function mouseMsg(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
const socket = io();

function setup() {
  createCanvas(400, 400);
  background(0);

  // Set up listener for incomming socket events
  socket.on('mouse', newDrawing);
}

const lineWidth = 10;

function newDrawing(data) {
  // Draw some white circles with different colors
  colorMode(RGB, 255);
  fill(255, 0, 100);
  noStroke();
  ellipse(data.x, data.y, lineWidth, lineWidth);
}

function mouseDragged() {
  let currentNumX = mouseX;
  let lowerBound = 0;
  let upperBoundX = width; //100;
  let normalizedX = norm(currentNumX, lowerBound, upperBoundX);
  let currentNumY = mouseY;
  let upperBoundY = height; //100;
  let normalizedY = norm(currentNumY, lowerBound, upperBoundY);
  colorMode(HSB, 255);
  let c = color(normalizedX * 255, normalizedY * 255, 255);
  // Draw some white circles
  fill(255);
  noStroke();
  ellipse(mouseX, mouseY, lineWidth, lineWidth);


  const data = {
    x: mouseX,
    y: mouseY,
  };

  console.log(`Sending ${data.x} ${data.y} `);
  socket.emit("mouse", data);
}

Serveren kan startes op med denne kommando.

npm run start