Same event emitting multiple times in socket.io-client reactjs - node.js

I am creating a chat app in react, expressjs and socket.io. When I click on Send Button, I am emitting an event and listening that event on server side and again emitting another event from server side and listening that event on client side. And I have written the event listening code on componentDidMount. But don't know why my client side calling same event multiple times. Below is my both side code:
Client side
var socketIOClient = require('socket.io-client')('http://localhost:4001');
sendMessageClicked(e) {
e.preventDefault();
let message = this.state.originalMessage;
var data = {
message: message,
time: Date.now()
}
socketIOClient.emit('send_message',data);
}
componentDidMount() {
socketIOClient.on('msg',function(result){
let messageHtml = 'messages working!';
let messageBox = document.getElementById('messageBox');
if (messageBox ) {
messageBox.appendChild(messageHtml);
}
})
}
render(){
return(
<div>
<form onSubmit={this.sendMessageClicked}>
<textarea onChange={this.handleMessageChange} name="originalMessage" value={this.state.originalMessage}></textarea>
<input type="submit" value="" />
</form>
</div>
);
}
Server side
const app = require('./app');
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4001);
io.on('connection',function(socket){
socket.on('send_message',function(data){
io.emit('msg',data);
})
})
Can anyone please help with the same?

I had the same issue, and I solved it with useEffect hook.
in your case it would be (on client side):
useEffect(()=>{
socket.on('msg', (result) => {
let messageHtml = 'messages working!';
let messageBox = document.getElementById('messageBox');
if (messageBox ) {
messageBox.appendChild(messageHtml);
})
return function cleanup() {socket.off('msg')}
},[])
I'm sure you could do this also with ComponentDidUpdate or ComponentDidUnmount, but useEffect is eassier.

In the useEffect() hook, checking if socket connection already exists using socket.current helped me get rid of this problem -
useEffect(() => {
(async () => {
if (!socket.current) {
socket.current = io(`http://localhost:8080/`)
.on("connect", () => {
//do something
});
socket.current.on("message", (instance) => {
//receive message from server
});
}
})();
});

Related

React + Nodejs/Express App to display products

I've got a simple React App with Nodejs/Express server.
Right now I'm trying to obtain an ID value from Serialport and compare that ID with the ID from an external webservice and retrieve the data I get from the webservice and display it on the frontend.
I've got the first part working and right now I can compare both ID's and fetch the data but can't figure out how to display it in the React frontend.
This is my server index.js:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname + "/public")));
const PORT = process.env.PORT || 5000;
const scanProducts = () => {
const scan = require('./actions/scanProduct');
scan.scanner();
//can't reach data here
}
app.listen(PORT);
scanProducts();
This is my scanProduct.js
const { SerialPort } = require('serialport');
module.exports = {
scanner: function(){
const port = new SerialPort({ path: 'COM6', baudRate: 9600, autoOpen: false });
port.open(function (err) {
if (err) {
return console.log('Error opening port: ', err.message)
}
port.write('main screen turn on')
})
port.on('open', function() {
setInterval(function(){
const portReader = port.read();
if(portReader != null){
const sensorVal = Buffer.from(portReader).toString();
const soap = require('soap');
const url = 'http://example.com?wsdl';
soap.createClient(url, function(err, client) {
client.GetProductById({ UserId: "1", ProductId: sensorVal }, function(err, result) {
if(err) return console.log(err);
console.log(result.GetProductByIdResult);
return result.GetProductByIdResult; //returns nothing into index.js
});
});
}
}, 500);
})
}
}
Then I would like to add each product from the server into this custom component, right now it displays static data fetched from a basic json file.
This my component ProductsList.js:
import ProductRow from "./ProductRow";
import './ProductsList.css';
const ProductsList = props => {
return(
<>
<div id="products-wrapper" className="w-9/12 h-full px-20 py-20 flex flex-col overflow-x-hidden overflow-y-scroll ">
<div className="w-full h-auto my-2 px-3 py-3 font-semibold grid grid-cols-3 bg-blue-600 rounded-xl">
<div className="w-[60%] text-left">Produto</div>
<div className="w-[20%] text-left">Quant.</div>
<div className="w-[20%] text-left">Preço</div>
</div>
{props.items.map(product => <ProductRow name={product.name} quantity={product.quantity} price={product.price}/>)}
//here is where I need to add each product from the server
</div>
</>
);
}
export default ProductsList;
Any idea what I might be missing?
Any help would be greatly appreciated.
A sample code for your project
I put some comments, I hope it will be easy to follow
I wrote some remarks at the end of the code too
Backend
For the index.js (main) file of your backend
const EventEmitter = require('events');
var cors = require('cors')
// Init express app
const app = require('express')();
// Import your scanner utility
const scan=require('./scanProduct')
/*Enabling CORS for any origin (host and port) to test the service from a another origin (react client) .
It depends how you deploy your services */
app.use(cors({
origin:'*'
}))
// Init the http server
const server = require('http').createServer(app);
// Init the websocket library
const io = require('socket.io')(server);
// Define some plain emitter
const emitter=new EventEmitter()
// Pass the event emitter in it
scan.scanner(emitter)
// Event fired when the websocket has been established
io.on('connection', socket => {
// When the scanProduct fire an event on scanner channel
emitter.on("scanner",function(data){
// Emit the data on the websocket for the react client
// You can define whatever name you prefer, here also scanner
socket.emit('scanner',data)
})
});
//Listening on port 8080
server.listen(8080);
And for the scanProduct.js file i just "mocked" your implementation with setInterval every 2 secs in my case
module.exports = {
scanner: function(eventEmitter){
// Read serial port every 2000ms
setInterval(()=>{
/*
- Read on serial port
- fetch the data from the soap web service
*/
// just some data to send but should be from your workflow
const productResult=new Date().toISOString()
// you emit on the channel you defined in the index.js file
eventEmitter.emit("scanner",productResult)
},2000)
}
}
The depedencies I am using on the backend
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"socket.io": "^4.6.0"
}
Frontend
For the front-end, I used npx create-react-app to init the project,
And I edited only one file, the App.js file
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
// Websocket initialization, use your config or .env file to set up the url
const websocket = io(
"http://localhost:8080",
{ transports: ['websocket'] }
)
function App() {
//State keeping all the products we are displaying
const [products, setProducts] = useState([])
//When App component is mounted
useEffect(() => {
// Just to log the connection
websocket.on('connection', () => {
console.log("Websocket connected")
})
// When websocket receive data on the scanner channel, emitted from the backend
websocket.on("scanner", (product) => {
// Update the products with new ones
setProducts(prevProducts => [...prevProducts, product])
})
}, [])
return (
<div>
<div>
Number of products : {products.length}
</div>
{
products.map((data) => {
return (
<div>
{data}
</div>
)
})
}
</div>
);
}
export default App;
My sample code as it is will send data every 2000ms and we will have en enormous list in no time ^^'.
For your use case, I do not know if it is relevant to send data every 500ms to the client.
Do you have continuous flow of valuable/usefull data on the serial port ? If you really have valuable data every 500ms, another approach would be more appropriate, like batching. The idea will be to save somewhere the products you collected every 500ms, and from titme to time, every 10 secondes for example, you send this list of new products to the client.
If the payload on the serial port arrives randomly, you need to build some logic into your setInterval function, and only trigger an event when necessary.
The sample of course lacks some features. You only have new products coming from the websocket, but no history. If you refresh your browser page or if the socket is closed for whatever reason, you are going to miss some products. If history is important, you need some persistence layer.

How to send real time notification with socket.io in express

I want to send a real-time notification to the owner of the post when the post is liked. But, I don't really have an idea how to implement it into my React app and make it work. My notification function on the server side looks like this;
const Notification = require("../models/NotificationModel.js");
const { Server } = require("socket.io");
const io = new Server({
cors: "clientURL",
});
const sendNotification = async ({
sender,
receiver,
message,
project,
comment,
challenge,
}) => {
io.on("connection", (socket) => {
socket.on("sendNotification", ({sender, receiver, message}) => {
io.to(receiver.socketId).emit("getNotification", {
sender,
message
})
});
});
await Notification.create({
message,
sender,
receiver,
project,
comment,
challenge,
});
};
module.exports = sendNotification;
According to the OpenGPT client-side should look like this;
import React, { useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('serverURL');
const MyComponent = () => {
useEffect(() => {
socket.on("getNotification", (data) => {
// Handle the notification with the data from the server
});
}, []);
return (
// Render your component
);
};
Could you please point out all the wrongs in this snippet and provide the correct way to make these actions in sequence;
user likes a post -> server sends a notification to the owner of the post

Socket IO Client not receiving events on reconnection

I have a file called socket_io.js where I created a single instance of a socket io client in my react app as shown below:
socket_io.js
import EndPoints from './http/endpoints';
import io from "socket.io-client";
const socketUrl = EndPoints.SOCKET_BASE;
let socketOptions = { transports: ["websocket"] }
let socket;
if (!socket) {
socket = io(socketUrl, socketOptions);
socket.on('connect', () => {
console.log(`Connected to Server`);
})
socket.on('disconnect', () => {
console.log(`Disconnected from Server`);
})
}
export default socket;
Then I imported the above singleton in many react components as shown below.
MessagePage.js
import socket from '../socket_io.js';
let messageHandler=(data)=>{
}
useEffect(()=>{
socket.on('message',messageHandler); //This event no longer fires When the singleton socket io instance is reconnected
return ()=>{
socket.off('message');
}
},[]);
which works well but the issue I'm facing now is that when the singleton instance reconnects, the components referencing it are no longer receiving events from their respective handlers.
Possible causes of reconnection are when I manually restart the server
How can this be resolved?
I just solved this after working on it for a project of my own. My method involves two parts: creating the socket in a useEffect hook and then managing it using useRef for reconnection situations.
In Summary:
I think there are two issues. One is that the socket is being initialized as a singleton and not using a hook/context. I've read other reports of strangeness in this case, so I suggest switching to using context and creating your socket in a hook. Secondly, we have to manually store reconnection logic (although by generating the socket properly, it seems as though the actual event listeners are kept through reconnect).
export const SocketContext = createContext();
export const SocketContextProvider = ({ children }) => {
const [socket, setSocket] = useState();
const reconnectEmits = useRef([]);
// Here's your basic socket init.
useEffect(()=>{
const newSocket = io(url);
setSocket(newSocket);
return () => {
newSocket.close();
}
}, []);
// Code used to rejoin rooms, etc., on reconnect.
newSocket.io.on('reconnect', e => {
console.log("it took " + e + " tries to reconnect.");
for (let action of reconnectEmits.current) {
newSocket.emit(action.event, action.data);
}
})
// Here I also define a setListener and removeListener function, which determine which listeners a socket listens to. I don't have the code in front of me now, but it's pretty simple:
const addListener = (event, function) => {
// I use socket.off(event) right here to make sure I only have one listener per event, but you may not want this. If you don't use it you will need to make sure you use hooks to remove the event listeners that your components add to your socket when they are removed from the DOM.
socket.on(event, function);
}
// I implement an emit function here that's a wrapper, but I'm not sure if it's necessary. You could just expose the socket itself in the context. I just choose not to.
return (
<SocketContext.Provider value={{ emit, setListener, removeListener, addReconnectEmit, removeReconnectEmit }}>
{children}
</SocketContext.Provider>
)
}
And then in my components, in addition to having the emits to join rooms or conduct actions, I also provide the add and remove ReconnectEmit functions:
const addReconnectEmit = (event, data) => {
reconnectEmits.current = ([...reconnectEmits.current, { event, data }]);
console.log(reconnectEmits.current);
}
const removeReconnectEmit = (event, data) => {
console.log('removing reconnect event');
reconnectEmits.current = reconnectEmits.current.filter(e =>
{ return e.event !== event && e.data !== data }
);
console.log(reconnectEmits.current);
};
With these, I can set it so that, after a reconnect, my socket knows to reconnect to a certain room, etc. See here:
const Chatroom = ({ convoId }) => {
console.log("RENDERED: Chatroom");
const { emit, addReconnectEmit, removeReconnectEmit } = useContext(SocketContext);
useEffect(() => {
emit('joinConvo', convoId);
console.log("Emitting joinConvo message.");
addReconnectEmit('joinConvo', convoId);
return () => {
emit('leaveConvo', convoId);
removeReconnectEmit('leaveConvo', convoId);
}
}, [convoId, emit, addReconnectEmit, removeReconnectEmit]);
return (
<div id="chatroom">
<ChatroomOutput />
<ChatroomStatus />
<ChatroomControls convoId={convoId} />
</div>
);
}
I hope that helps! Between useEffect and manual reconnection logic, I just fixed similar issues to the ones you were having, where I was losing data on reconnection.
Saw you just answered yourself but my approach might still be valuable for others or if you continue to build a socket-client.
You need to abstract the listening components away from the socket object. The socket object upon onMessage needs to retrieve the subscribers and publish the new message to them. You can of course add filtering based on id, type or other properties. Also each component can drop its subscription when un-mounting or based on another need.
In order to show case I used timers but would be easily converted to messages.
socket_io.js
let socket;
const subscribers = []
if (!socket) {
// socket initial connect
socket = true
setInterval(() => {
console.log('interval runs', { socket })
if (socket) {
subscribers.forEach((sub) => {
sub.onMessage()
})
}
}, 1000)
setTimeout(() => {
// socket disconnects
socket = false
setTimeout(() => {
// socket reconnects
socket = true
}, 4000)
}, 4000)
}
export default subscribers;
MessagePage.js
import React, { useEffect, useState } from 'react'
import subscribers from './socket_io.js'
const MessagePage = () => {
const [messageCount, setMessageCount] = useState(0)
let messageHandler = (data) => {
setMessageCount((current) => current + 1)
}
useEffect(() => {
subscribers.push({
id: '1',
onMessage: (data) => messageHandler(data)
})
return () => {
const subToRemove = subscribers.findIndex((sub) => sub.id === '1')
subscribers.splice(subToRemove, 1)
}
}, []);
return (
<div>
Messages received: {messageCount}
</div>
)
}
export default MessagePage
Hope I could help.
export default expects a Hoistable Declarative , i.e function,express
socket_oi.js
import EndPoints from './http/endpoints';
import io from "socket.io-client";
const socketUrl = EndPoints.SOCKET_BASE;
let socketOptions = { transports: ["websocket"] }
let socket;
class Socket {
constructor (){
if (!socket) {
socket = io(socketUrl, socketOptions);
socket.on('connect', () => {
console.log(`Connected to Server`);
})
socket.on('disconnect', () => {
console.log(`Disconnected from Server`);
})
}
socket = this
}
}
//Freeze the object , to avoid modification by other functions/modules
let newSocketInstance = Object.freeze(new Socket)
module.exports = newSocketInstance;
MessagePage.js
import socket from '../socket_io.js';
const MessagePage = (props){
const messageHandler=(data)=>{
}
useEffect(()=>{
socket.on('message',messageHandler); //This event no longer fires When the
singleton socket io instance is reconnected
return ()=>{
socket.off('message');
}
},[]);
}

Next.js (React.js), with Node.js server Socket.io client multiple IDs

I'm having an issue where my React app is outputting the same one ID on every page that it loads, where as Backend Node.js Socket.io server is outputting multiple client IDs whenever I change route in my app...
Server:
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000",
},
});
io.on("connection", (socket) => {
console.log("client connected: ", socket.id);
socket.on("disconnect", (reason) => {
console.log("disconnect", reason);
});
});
App.js:
useEffect(() => {
console.log("use effect", socket.id);
return () => {
socket.off("connect");
socket.off("disconnect");
};
}, []);
Socket.ts:
import io from "socket.io-client";
const socket = io(`${process.env.NEXT_PUBLIC_SOCKET_IO_URL}`);
socket.on("connect", () => console.log("socket_id", socket.id));
export default socket;
server.js (backend - websocket)
const io = new Server(httpServer, {
cors: {
origin: "http://localhost:3000",
},
});
io.on("connection", (socket) => {
console.log("client connected: ", socket.id);
socket.on("disconnect", (reason) => {
console.log("disconnect", reason);
});});
First of all, socket.io server sometimes generates a new id due reconnections or others things:
https://socket.io/docs/v4/server-socket-instance/#socketid
So if you are planning keep the same id, i disencourage you.
Well, but looks you are wondering about fast recriation of ids. React is rendering according state changes, so create a stateless connection inside some component cause this behaviour. Yon can choose a lot of solutions but, i will present you a solution extensible, ease to mantain and deliver to componets the role of subscribe and unsubscribe to itself listeners, this sounds better than have a global listeners declaration :D
1. Create Socket Context
We will use useContext hook to provide SocketContext to entire app.
Create a file in context/socket.js:
import React from "react"
import socketio from "socket.io-client"
import { SOCKET_URL } from "config"
export const socket = socketio.connect(SOCKET_URL)
export const SocketContext = React.createContext()
2. Use socket context and provide a value
Add SocketContext provider at the root of your project or at the largest scope where socket is used:
import {SocketContext, socket} from 'context/socket';
import Child from 'components/Child';
const App = () => {
return (
<SocketContext.Provider value={socket}>
<Child />
<Child />
...
</SocketContext.Provider
);
};
3. Now you can use socket in any child component
For example, in GrandChild component, you can use socket like this:
import React, {useState, useContext, useCallback, useEffect} from 'react';
import {SocketContext} from 'context/socket';
const GrandChild = ({userId}) => {
const socket = useContext(SocketContext);
const [joined, setJoined] = useState(false);
const handleInviteAccepted = useCallback(() => {
setJoined(true);
}, []);
const handleJoinChat = useCallback(() => {
socket.emit("SEND_JOIN_REQUEST");
}, []);
useEffect(() => {
// as soon as the component is mounted, do the following tasks:
// emit USER_ONLINE event
socket.emit("USER_ONLINE", userId);
// subscribe to socket events
socket.on("JOIN_REQUEST_ACCEPTED", handleInviteAccepted);
return () => {
// before the component is destroyed
// unbind all event handlers used in this component
socket.off("JOIN_REQUEST_ACCEPTED", handleInviteAccepted);
};
}, [socket, userId, handleInviteAccepted]);
return (
<div>
{ joined ? (
<p>Click the button to send a request to join chat!</p>
) : (
<p>Congratulations! You are accepted to join chat!</p>
) }
<button onClick={handleJoinChat}>
Join Chat
</button>
</div>
);
};
What is useContext?
useContext provides a React way to use global state,
You can use context in any child component,
Context values are states. React notices their change and triggers re-render.
What is useCallback? Why did you put every handlers inside useCallback?
useCallback prevents reassigning whenever there is state update
Functions will be reassigned only when elements in the second argument are updated
More reference:
https://www.w3schools.com/react/react_usecallback.asp
This nice tutorial has obtained in:
https://dev.to/bravemaster619/how-to-use-socket-io-client-correctly-in-react-app-o65

Implementing a collaborative text editor using nodejs/react/socket but encountering problems because of slow heroku servers

I've tried making a collaborative editor using socket.io with reactjs frontend and node backend. Here's the piece of logic which I think is causing problems....
When a client starts typing on the editor, I've used onInput event to emit a socket response say "typing" which carries the complete text on the editor inside data object at the moment client presses a key. Now server catches this typing event and in response to that, emits another socket response called "typed" which contains the same data but the server sends this response to all the clients connected to the server.... Now all clients receive this event inside componentDidMount and then update the state variable "codeValue" which updates the editor content for all the clients.
There are two problems, first one that on one single typing event, server is emitting numerous typed events ( it happens only in heroku server and not on local host ) and the other problem is that heroku servers are slow and before the server sends response to update the state of clients, clients had already entered more text on the editor which simply vanishes when the state is updated.....
FRONTEND CODE:
import React from "react";
import { Dropdown } from "semantic-ui-react";
import languages from "../utils/languages";
//Styles
import "../styles/app.css";
//Editor
import * as ace from "ace-builds";
// import SocketIOClient from "socket.io-client";
import "ace-builds/src-noconflict/mode-c_cpp";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/ext-language_tools";
import AceEditor from "react-ace";
let check = true;
let ld;
// const endpoint = "http://localhost:4676";
// const socket = SocketIOClient(endpoint, { transports: ["websocket"] });
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
codeValue: languages[0].template,
currentLang: languages[0].key,
};
this.codeEditor = React.createRef();
this.fireTyping = this.fireTyping.bind(this);
this.onDDChange = this.onDDChange.bind(this);
this.runCode = this.runCode.bind(this);
this.handleOutput = this.handleOutput.bind(this);
}
componentDidMount() {
this.props.socket.on("typed", (data) => {
console.log(35, data.text)
this.setState({
codeValue: data.text,
});
check = true;
console.log(check)
});
this.props.socket.on('ans',(data) => {
console.log(data.output)
//handleOutput(data.output)
})
}
fireTyping = () => {
ld = this.codeEditor.current.editor.getValue()
//console.log(ld)
if(check) {
console.log(48, this.codeEditor.current.editor.getValue(), check);
this.props.socket.emit("typing", {
text: ld,
});
check = false;
}
console.log(check)
};
onDDChange = (e, data) => {
const selectedVal = languages.filter((v) => v.key == data.value)
this.setState({currentLang : data.value, codeValue: selectedVal[0].template})
}
runCode = () => {
this.props.socket.emit('run', {
code: this.codeEditor.current.editor.getValue(),
lang: this.state.currentLang,
input: ''
})
}
handleOutput = () => {
}
render() {
return (
<div>
<Dropdown
placeholder="Languages"
onChange = {this.onDDChange}
selection
value = {this.state.currentLang}
options={languages}
/>
<AceEditor
style={{
margin: "3rem auto",
width: "80vw",
height: "70vh",
}}
fontSize={18}
ref={this.codeEditor}
mode="c_cpp"
theme="github"
value={this.state.codeValue}
onInput={this.fireTyping}
showPrintMargin={false}
name="UNIQUE_ID_OF_DIV"
editorProps={{ $blockScrolling: true }}
setOptions={{
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
}}
/>
<div className="container">
<button
onClick={this.runCode}
style={{
marginLeft: "40rem",
}}
className="large ui teal button"
>
Run
</button>
</div>
</div>
);
}
}
export default App;
BACKEND CODE:
const express = require("express");
const request = require("request");
const app = express();
const http = require("http");
const server = http.createServer(app);
const path = require('path')
const socket = require("socket.io");
const io = socket(server);
const port = process.env.PORT || 4676
app.use(express.static(path.join(__dirname, 'client/build')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
io.on("connection", (socket) => {
let previousCode, currentCode;
console.log(socket.id);
socket.on("typing", (data) => {
currentCode = data.text
console.log('typing')
console.log(previousCode === currentCode)
if(previousCode !== currentCode){
console.log(1)
io.emit("typed", data);
previousCode = currentCode;
currentCode = ''
}
});
});
server.listen(port, () => {
console.log("server started at http://localhost:4676");
});
I've spent hours trying to fix this but I couldn't.... Any help would be appreciated ☺️
Let me know if you need code reference, I'll share the repository

Resources