Play around with Socket.io and Typescript
I heard about socket.io many time, reading what it can do and benefit of socket.io but never have to play with it. at Medvine we have application that use socket.io to control even of application. so I decide to get my hand dirty and start playing with it. of course I will integrate with Typescript — the best subset of javascript language.
What is Socket.io
Socket.io is javascript library design for long-pull connection between browser and server. which mean data will update every time if server got data from browser. then server will update data and send to browser again. the best example in real world that can use this technology is chat application. when someone join that room and type somethings. that massage will send to server and server will response back by send that message to all user.
On picture above Socket.io is watching hashtag on twitter. if some one tweet about watching hashtag. web application will display it on realtime.
So what is challenge for today?
We will create one application. this application will connect to demo website for grab user information by using Axios and grab it by async function(parallel request). like this picture
All 50 request will fire from application in one time. all data will fire to server without waiting for response. and when all of it complete we need Socket-io to show which one is complete.
OK. let start Implement this one.
first we need to create new folder for this project. then start create package.json by using this command
yarn init -y
Then install these packages.
yarn add axios express http socket.io socket.io-client
And dev dependencies packages.
yarn add @types/express @types/socket.io @types/socket.io-client concurrently nodemon typescript -D
You will notice we use typescript. so we need to install all of types and we use concurrently for execute 2 command in one time for running Typescript complier code and nodemon for watching file which file is changing. add this script to package.json file
"scripts": {
"dev": "concurrently \"tsc -w\" \"nodemon dist/app.js\""
},
Our package.json file will be like this.
tsconfig.json file.
When we use Typescript. this file will be typescript setting. most of the time we will use same pattern. just copy and past this code
if you want more explanation. see this article Combine Typescript with NextJS and Express
Hello world from Express
We need to use Express to display some message. for make sure we can working on server side. we need to put these code on file app.ts
import express, { Request, Response } from 'express';
const app = express();
const server = require('http').Server(app);
const port = 3000;app.get('/', (req: Request, res: Response) => {
res.json({ data: 'hello world' });
});server.listen(port, () => console.log(`Example app listening on port ${port}!`));
Then run command
yarn dev
This command will complier app.ts file to dist/app.js file which is we have nodemon to watching it. when nodemon got file. will running server on port 3000. you will see result at http://localhost:3000/
Socket.io and Axios
We need socket.io to know when Axios request to get users data success. but firstly we need to create room for socket.io for waiting event from socket.io-client.
import ioserver, { Socket } from 'socket.io';
import ioclient from 'socket.io-client';
const io = ioserver(server);io.on('connection', (socket: Socket) => {
socket.on('my other event', (data) => {
console.log('I got data. will running another function', data.count);
});
});
And create function fetchUsers
const fetchUsers = (socketclient: SocketIOClient.Socket, incrementId: number) => {
// fetch data and send response back to socket io.
const fetchUsers = axios
.get('https://jsonplaceholder.typicode.com/users')
.then((result) => {
socketclient.emit('my other event', { data: result.data, count: incrementId });
return result.data;
})
.catch((error) => error.message);return fetchUsers;
};
When fetch user complete. socket.io-client will send message to notify to socket.io and socket.io will process and show message which request is complete.
This is code for complete file
And this is result. all request will fire to server in same time and response will come back.
So we can do more things with this concept like process that response when response come back from server. add them to database or notify to user that we got data already. it depend on you design.
If you like this article don’t forget to give me some clap. any suggestion are welcome on comment section.
I appreciated all cup of coffee. you can donate coffee at button below.
get code on my github.