Skip to content

Create the Socket.IO Server

Video Lecture

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

 (Pay Per View)

You can use PayPal to purchase a one time viewing of this video for $1.49 USD.

Pay Per View Terms

  • One viewing session of this video will cost the equivalent of $1.49 USD in your currency.
  • After successful purchase, the video will automatically start playing.
  • You can pause, replay and go fullscreen as many times as needed in one single session for up to an hour.
  • Do not refresh the browser since it will invalidate the session.
  • If you want longer-term access to all videos, consider purchasing full access through Udemy or YouTube Memberships instead.
  • This Pay Per View option does not permit downloading this video for later viewing or sharing.
  • All videos are Copyright © 2019-2025 Sean Bradley, all rights reserved.

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.