84
loading...
This website collects cookies to deliver better user experience
React
and Socket.io
.We will be using expressJS on top of NodeJS as a backend.Read more of these stories on my website.
nodejs
project first.directory
and then enter it.mkdir socketio-node
socketio-node
.expressJS
. Make sure NodeJS is installed on your system.package.json
manifest file that describes our project.npm init
){
"name": "socketio-node",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
dependencies
property we need to install express
, type this in the terminal.npm install express
dependencies
will now look like. The version can be different depending on the latest version at the time you install it."dependencies": {
"express": "^4.17.1"
}
index.js
file that will setup our application.const app = require('express')();
const http = require('http').createServer(app);
app.get('/', (req, res) => {
res.send('<h1>Hey Socket.io</h1>');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
app
to be a function handler that you can supply to an HTTP server (as seen in line 2)./
that gets called when we hit our website home.socket.io
dependency into our app. Run this in the terminal.npm install socket.io
package.json
. Now let’s edit index.js
to add it:const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:3001']
}
});
app.get('/', (req, res) => {
res.send('<h1>Hey Socket.io</h1>');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
socket.io
on line 3 by passing the http
(the HTTP server) object and the cors options(updated for socket.io v3) to allow our react localhost url, you can put in the url or your frontend client, in my case it was localhost:3001
connection
and disconnection
events for incoming sockets, and I log it to the console.node
code when we will implement more events further on.React
app now. I will be creating a new React
app from scratch with create-react-app
, while most of you would already have one created with you.React
app can skip the following code:npx create-react-app socketio-react
CRA
and create a new template React app from scratch.dependency
in our React app.cd socketio-react
npm install socket.io-client
socket.io-client
library in our React app.file
to handle socket.io connection. I would create a root level file named socketio.service.js
and include that in the src
folder.cd src
touch socketio.service.js
import { io } from 'socket.io-client';
touch .env
REACT_APP_SOCKET_ENDPOINT=http://localhost:3000
REACT_APP
as a prefix as it is needed by create-react-app
. For more details you can check this link.socketio.service.js
and write a socket init function.import { io } from 'socket.io-client';
let socket;
export const initiateSocketConnection = () => {
socket = io(process.env.REACT_APP_SOCKET_ENDPOINT);
console.log(`Connecting socket...`);
}
socket
and then after calling the initiateSocketConnection
function, socket
connect would be initialized on the URL
provided in .env
file and socket
variable would be containing the connected socket object..env
file like this process.env.yourvariablename
.App.js
file and lets make use of the hooks. We will use useEffect
hook which would only run once on render since we have to init the socket connection only once.import { useEffect } from 'react';
function App() {
useEffect(() => {
initiateSocketConnection();
}, []);
}
Note: I am importing only { useEffect } from 'react'; but not import React, {useEffect} from 'react'; since i am on React 17 and it doesn't need that, if you are on old versions(< 17) you might end up importing the last one.
PORT=3001 npm start
import { useEffect } from 'react';
function App() {
useEffect(() => {
initiateSocketConnection();
return () => {
disconnectSocket();
}
}, []);
}
socketio.service.js
file add this for disconnectionexport const disconnectSocket = () => {
console.log('Disconnecting socket...');
if(socket) socket.disconnect();
}
user disconnected
message on console.my message
inside our index.js
node file and console the data and we will emit the same event from React
app.io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('my message', (msg) => {
console.log('message: ' + msg);
});
});
export const subscribeToChat = (cb) => {
socket.emit('my message', 'Hello there from React.');
}
useEffect
where we initialized our socket connection in App.jsuseEffect(() => {
initiateSocketConnection();
subscribeToChat((err, data) => {
console.log(data);
});
return () => {
disconnectSocket();
}
}, []);
emit
an event from the server side
to client side. We will broadcast the event to all connected users. We will broadcast the same message that we received from client and prepend a server string to it.io.on('connection', (socket) => {
socket.on('my message', (msg) => {
io.emit('my broadcast', `server: ${msg}`);
});
});
my broadcast
event on our React
app now.export const subscribeToChat = (cb) => {
socket.emit('my message', 'Hello there from React.');
socket.on('my broadcast', msg => {
return cb(null, msg);
});
}
my broadcast
event and call the registered callback in App.jsauthentication parameters
to the Backend when connecting to the socket by using auth
object in options in a connection.export const initiateSocketConnection = (room) => {
socket = io(process.env.REACT_APP_SOCKET_ENDPOINT, {
auth: {
token: 'cde'
},
});
console.log(`Connecting socket...`);
}
fetch
this information on the Backend, we have to do it like this:io.on('connection', (socket) => {
let token = socket.handshake.auth.token;
});
cde
passed by Frontend.You can check all of the above written example code at my github.
real time application
with React
and Socket.io
with NodeJS
and ExpressJS
.The next part of this article which explains the concept of rooms, realtime one to one chat and group chat is here.
Read more of these stories on my website.