[Web Devlopement] What Are Websockets and Why Would You Use Them?
How's your web site working? Normally it works like that
clients send request to server and server answers it. However, if something change is happened at server and we want to inform a client?
1. Websockets, It Is a Kind of Protocol
Websockets are protocol which push data form server to clients
2. Start at Backend Project First.
In order to user socket.io you have to install socket.io into both project backend and frontend. First of all, we go to backend first
Let's change your app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | mongoose .connect( "mongodb+srv://matthias:password@node-complete.cqski.mongodb.net/myFirstDatabase?retryWrites=true&w=majority" ) .then((result) => { const server = app.listen(8080); const io = require('socket.io')(server) io.on('connection', socket => { console.log('Client Connected') }) }) .catch((err) => { console.log(err); }); | cs |
3. Install socket.io-client Into Your Frontend
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import openSocket from 'socket.io-client'; componentDidMount() { fetch('http://localhost:8080/auth/status', { headers: { Authorization: 'Bearer ' + this.props.token } }) .then(res => { if (res.status !== 200) { throw new Error('Failed to fetch user status.'); } return res.json(); }) .then(resData => { this.setState({ status: resData.status }); }) .catch(this.catchError); this.loadPosts(); openSocket('http://localhost:8080'); } | cs |
4. Result
Congratulation! You did it! now the server push the information updated or added from server!