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/

Note

If both the tsc and tsc.cmd commands are not working, then you should install TypeScript globally on your system using the command,

npm install -g typescript

Now, if the compilation worked correctly, there should be 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

Troubleshooting

Error The term 'tsc.cmd' is not recognized as the name of a cmdlet, function, script file, or operable program.

If neither tsc or tsc.cmd works, and throws the error similar to The term 'tsc.cmd' is not recognized as the name of a cmdlet, then you can install TypeScript globally.

npm install -g typescript

Now to test if TypeScript is installed, run tsc -v or tsc.cmd -v depending on which terminal program you are using. It should return a version number.