Create local dev WebSocket server using socket.io and NodeJs

yahone chow
2 min readSep 1, 2021

For best practice you should separate your server project and client project.

Server side

  1. npm install socket.io
"dependencies": {
"socket.io": "^4.1.3"
}

2. made a index.js file under your project’s directory root and write some simple code.

// import socket.io
const SI = require('socket.io');
// get NodeJs built-in module
const https = require('https');
// create your htts-server
var httpsServer = https.createServer(options);
// these setting means you permits specific origin's access.
const IOOptions = {
cors : {
origin : '192.168.0.123:8083',
// methods: ["*"],
methods : ['GET', 'POST']
}
}
// create your socket server
const io = SI(httpsServer, IOOptions);
// watch events
io.on('connection', client => {
console.log(client);
});
// listen port
httpsServer.listen(3000);

That’s all we need . run node index.js , there you go.

If you have properly configured your server (see above), this could mean that your browser wasn’t able to reach the Socket.IO server.The following command:// curl "https://api.example.com/socket.io/?EIO=4&transport=polling"should return something like:0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}

socket.io troubleshooting

Client Side

Since our websocket server running over https, while you access a WSS server CORS-ly, you need made your client https too.

  1. create cert files
openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

2. copy key.pem and cert.pem to your client server’s root directory

3. config your https server

For webpack user

devServer:{
http2 : true,
https : {
key : fs.readFileSync('key.pem'),
cert : fs.readFileSync('cert.pem')
},
..config
}

for NodeJs user

const options = {
key : fs.readFileSync('key.pem'),
cert : fs.readFileSync('cert.pem')
};
var httpsServer = https.createServer(options);

for http-server

hs -S -C -K

4. made html and js files

5. in you js file

const fs = require('fs');
const https = require('https');
const SI = require('socket.io');
const options = {
key : fs.readFileSync('key.pem'),
cert : fs.readFileSync('cert.pem')
};
const httpsServer = https.createServer(options);
io.on('connection', socket => {
// do sth
});

Here to check sample code.

--

--