Skip to content

Socket.IO with Node.js, Express and Webpack

Video Lecture

Socket.IO with Node.js, Express and Webpack Socket.IO with Node.js, Express and Webpack

Description

We will now set up a small Threejs example that uses Socket.IO. Socket.IO will be served using the Node.js and Express server that we set up in the last lesson. Our web client will still be bundled using Webpack.

Socket.IO enables real-time, bidirectional and event-based communication between the browser clients and the Node.js server.

Communicating Between Server and Clients

In this example, each client will connect and continually broadcast its position and rotation to the server.

The server then continually updates all the connected clients with the positions and rotations of every other connected client.

The scene will show a new cube for each connection, and also show its position and rotation as it changes in real time. Each client will camera.lookAt() their own cube.

SocketIO Clients

./src/server/server.ts

Replace your ./src/server/server.ts with the script below and install Socket.IO

npm install socket.io
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import express from 'express'
import path from 'path'
import http from 'http'
import { Server, Socket } from 'socket.io'

const port: number = 3000

class App {
  private server: http.Server
  private port: number

  private io: Server
  private clients: any = {}

  constructor(port: number) {
    this.port = port
    const app = express()
    app.use(express.static(path.join(__dirname, '../client')))

    this.server = new http.Server(app)

    this.io = new Server(this.server)

    this.io.on('connection', (socket: Socket) => {
      console.log(socket.constructor.name)
      this.clients[socket.id] = {}
      console.log(this.clients)
      console.log('a user connected : ' + socket.id)
      socket.emit('id', socket.id)

      socket.on('disconnect', () => {
        console.log('socket disconnected : ' + socket.id)
        if (this.clients && this.clients[socket.id]) {
          console.log('deleting ' + socket.id)
          delete this.clients[socket.id]
          this.io.emit('removeClient', socket.id)
        }
      })

      socket.on('update', (message: any) => {
        if (this.clients[socket.id]) {
          this.clients[socket.id] = message // relaying the complete message
        }
      })
    })

    setInterval(() => {
      this.io.emit('clients', this.clients)
    }, 50)
  }

  public Start() {
    this.server.listen(this.port, () => {
      console.log(`Server listening on port ${this.port}.`)
    })
  }
}

new App(port).Start()

./src/client/client.ts

Replace your ./src/client/client.ts with the script below and install Socket.IO-Client

npm install socket.io-client
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import { GUI } from 'dat.gui'
import { io } from 'socket.io-client'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)

const geometry = new THREE.BoxGeometry()
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true,
})

const myObject3D = new THREE.Object3D()
myObject3D.position.x = Math.random() * 4 - 2
myObject3D.position.z = Math.random() * 4 - 2

const gridHelper = new THREE.GridHelper(10, 10)
gridHelper.position.y = -0.5
scene.add(gridHelper)

camera.position.z = 4

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
  render()
}

let myId = ''
let timestamp = 0
const clientCubes: { [id: string]: THREE.Mesh } = {}
const positions: { [id: string]: THREE.Vector3 } = {}
const quaternions: { [id: string]: THREE.Quaternion } = {}
const socket = io()
socket.on('connect', function () {
  console.log('connect')
})

socket.on('disconnect', function (message: any) {
  console.log('disconnect ' + message)
})

socket.on('id', (id: any) => {
  myId = id
  setInterval(() => {
    socket.emit('update', {
      t: Date.now(),
      p: myObject3D.position,
      q: myObject3D.quaternion,
    })
  }, 50)
})

socket.on('clients', (clients: any) => {
  let pingStatsHtml = 'Socket Ping Stats<br/><br/>'

  Object.keys(clients).forEach((c) => {
    timestamp = Date.now()
    pingStatsHtml += c + ' ' + (timestamp - clients[c].t) + 'ms<br/>'

    if (!clientCubes[c]) {
      clientCubes[c] = new THREE.Mesh(geometry, material)
      clientCubes[c].name = c
      scene.add(clientCubes[c])
    } else {
      clients[c].p && (positions[c] = clients[c].p)
      clients[c].q && (quaternions[c] = new THREE.Quaternion(...clients[c].q))
    }
  })
  ;(document.getElementById('pingStats') as HTMLDivElement).innerHTML = pingStatsHtml
})

socket.on('removeClient', (id: string) => {
  scene.remove(scene.getObjectByName(id) as THREE.Object3D)
})

const stats = new Stats()
document.body.appendChild(stats.dom)

const gui = new GUI()
const cubeFolder = gui.addFolder('Cube')
const cubePositionFolder = cubeFolder.addFolder('Position')
cubePositionFolder.add(myObject3D.position, 'x', -5, 5)
cubePositionFolder.add(myObject3D.position, 'z', -5, 5)
cubePositionFolder.open()
const cubeRotationFolder = cubeFolder.addFolder('Rotation')
cubeRotationFolder.add(myObject3D.rotation, 'x', 0, Math.PI * 2, 0.01)
cubeRotationFolder.add(myObject3D.rotation, 'y', 0, Math.PI * 2, 0.01)
cubeRotationFolder.add(myObject3D.rotation, 'z', 0, Math.PI * 2, 0.01)
cubeRotationFolder.open()
cubeFolder.open()

const animate = function () {
  requestAnimationFrame(animate)

  controls.update()

  Object.keys(clientCubes).forEach((c, i) => {
    positions[c] && clientCubes[c].position.lerp(positions[c], 0.1)
    quaternions[c] && clientCubes[c].quaternion.slerp(quaternions[c], 0.1)
  })

  render()

  stats.update()
}

const render = function () {
  renderer.render(scene, camera)
}

animate()

./dist/client/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Three.js TypeScript Tutorials by Sean Bradley : https://sbcode.net/threejs</title>
    <style>
      body {
        overflow: hidden;
        margin: 0px;
      }

      #pingStats {
        position: absolute;
        top: 60px;
        left: 4px;
        width: 400px;
        height: 400px;
        pointer-events: none;
        color: white;
        font-family: monospace;
      }
    </style>
  </head>

  <body>
    <div id="pingStats"></div>
    <script type="module" src="bundle.js"></script>
  </body>
</html>

./package.json

Open ./package.json and replace the dev script with this below.

1
2
3
4
5
6
7
8
9
{
...
  "scripts": {
    "build": "webpack --config ./src/client/webpack.prod.js",
    "start": "node ./dist/server/server.js",
    "dev": "concurrently -k \"tsc -p ./src/server -w\" \"nodemon ./dist/server/server.js\" \"webpack serve --config ./src/client/webpack.dev.js\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
...

This new dev command will use

  • nodemon : so that it auto restarts Node.js whenever the server script is updated,
  • concurrently : so that we can run webpack, nodemon and TSC in watch mode using the same terminal. If we didn't use concurrently, then we could instead start the 3 processes individually in their own terminals. Concurrently makes it easier to start multiple processes at the same time.
  • webpack : This is the same as before. It will use the Webpack Dev Server with the ./src/client/webpack.dev.js configuration.

We will need to install nodemon and concurrently

npm install nodemon --save-dev
npm install concurrently --save-dev

./src/client/webpack.dev.js

Replace your ./src/client/webpack.dev.js with the script below.

Note the extra proxy information that tells the Webpack Dev Server where to redirect client requests for /socket.io. The Node.js and Express server will host and start the Socket.IO server on address http://127.0.0.1:3000

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const { merge } = require('webpack-merge')
const common = require('./webpack.common.js')
const path = require('path')

module.exports = merge(common, {
  mode: 'development',
  devtool: 'eval-source-map',
  devServer: {
    static: {
      directory: path.join(__dirname, '../../dist/client'),
    },
    hot: true,
    proxy: [
      {
        context: ['/socket.io'],
        target: 'http://localhost:3000',
        ws: true,
      },
    ],
  },
})

Example Socket.IO Projects

First Car Shooter

Multiplayer FCS written in Three.js, SocketIO and with client and server side CannonJS physics.

Game : https://fcs.sbcode.net/

Source Code : https://github.com/Sean-Bradley/First-Car-Shooter

First Car Shooter

Straight Car

Game : https://sc.sbcode.net

Source : https://github.com/Sean-Bradley/Straight-Car

Straight Car Multi Player

BirdMMO

A Multiplayer Flappy Bird Clone written in React Three Fiber, Threejs and Socket.IO

BirdMMO Game : https://birdmmo.sbcode.net

GitHub : https://github.com/Sean-Bradley/BirdMMO

Comments