Socket.IO with Node.js, Express and Webpack
Video Lecture
Your browser does not support the video tag.
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.
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.
./src/server/server.ts
Replace your ./src/server/server.ts
with the script below and 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
60
61 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 ]. t = message . t //client timestamp
this . clients [ socket . id ]. p = message . p //position
this . clients [ socket . id ]. r = message . r //rotation
}
})
})
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146 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 { TWEEN } from 'three/examples/jsm/libs/tween.module.min'
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 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 ,
r : myObject3D.rotation ,
})
}, 50 )
})
socket . on ( 'clients' , ( clients : any ) => {
let pingStatsHtml = 'Socket Ping Stats<br/><br/>'
Object . keys ( clients ). forEach (( p ) => {
timestamp = Date . now ()
pingStatsHtml += p + ' ' + ( timestamp - clients [ p ]. t ) + 'ms<br/>'
if ( ! clientCubes [ p ]) {
clientCubes [ p ] = new THREE . Mesh ( geometry , material )
clientCubes [ p ]. name = p
scene . add ( clientCubes [ p ])
} else {
if ( clients [ p ]. p ) {
new TWEEN . Tween ( clientCubes [ p ]. position )
. to (
{
x : clients [ p ]. p . x ,
y : clients [ p ]. p . y ,
z : clients [ p ]. p . z ,
},
50
)
. start ()
}
if ( clients [ p ]. r ) {
new TWEEN . Tween ( clientCubes [ p ]. rotation )
. to (
{
x : clients [ p ]. r . _x ,
y : clients [ p ]. r . _y ,
z : clients [ p ]. r . _z ,
},
50
)
. start ()
}
}
})
;( 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 ()
TWEEN . update ()
if ( clientCubes [ myId ]) {
camera . lookAt ( clientCubes [ myId ]. position )
}
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
31
32
33 <!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 : 0 px ;
}
# pingStats {
position : absolute ;
top : 60 px ;
left : 4 px ;
width : 400 px ;
height : 400 px ;
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.
{
...
"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 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 : {
'/socket.io' : {
target : 'http://127.0.0.1:3000' ,
ws : true ,
},
},
},
})