Skip to content

Create the Socket.IO Server

Video Lecture

Create the Socket.IO Server Create the Socket.IO Server

Description

We are going to create, compile and start a simple Socket.IO server.

First, create the server script.

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import { createServer } from 'http'
import { Server } from 'socket.io'

const port = 3000

const server = createServer()

const io = new Server(server)

io.on('connection', (socket) => {
  console.log('a user connected : ' + socket.id)
})

server.listen(port, () => {
  console.log('Server listening on port ' + port)
})

Next, we need to install the socket.io package.

npm install socket.io

Now we can transpile this TypeScript code into JavaScript code that Node.js can run.

tsc.cmd ./src/server/server.ts --outDir ./dist/server/

This should have created a new JavaScript file named server.js in the ./dist/server/ folder.

Now we can execute the server.js file.

node ./dist/server/server.js