'After second emit, socket.io throw net::ERR_CONNECTION_REFUSED error
I send a message from backend to the front-end with socket.io and I can see it. But after I try manually to add a second one I got a connection refused error. Why is this? How can I solve it?
Backend code:
const options = {
cors: true,
origins: ["http://127.0.0.1:" + port],
};
const io = new Server(server, options);
/**
* socket connections
*/
io.use((socket, next) => {
if (socket?.handshake?.auth?.token) {
new Promise((resolve, reject) => {
jwt.verify(socket.handshake.auth.token, "Bearer", (error, result) => {
if (error) reject(next(new Error(error)));
resolve(next());
});
});
} else {
next(new Error("invalid"));
}
}).on("connection", async function (socket) {
socket.on("hi", (a) => console.log(a.toUpperCase()));
console.log("is this working?? ");
// console.log("DB ", Log);
socket.emit("message", "socket connection is up"); ;
try {
Log.log.addHook("afterSave", "notifyUsers", (log, options) => {
console.log("NEW LOG ???", log);
socket.emit("logs", log);
});
} catch (error) {
console.log("ERRR ", error);
}
});
Front-end:
const socket = io(API_URL, {
reconnectionDelayMax: 10000,
auth: {
token: localStorage.getItem("access_token"),
},
});
props.setSocket(socket);
socket.emit("hi", "Hello from client!");
socket.on("message", function (data) {
console.log("message ", data);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
