Answer the question
In order to leave comments, you need to log in
How to split socket io logic into files (routes) in express js?
I am making an application.
Frontend on Vue JS
Backend on Node JS(express)
There is a common file with socket.io methods - server.js Everything is described
in this file.
I would like to move the methods for each route to a separate file, and have each component on the client listen and send messages only to a specific route.
Current result:
Во vue js в кмопоненте прописан роут, по которому нужно отправлять или слушать методы:
import io from "socket.io-client";
const socket = io("http://localhost:11050");
created() {
this.$socket.$subscribe("newNumber", (user) => {
this.addUser(user);
});
},
addUser(user) {
console.log(user);
this.usersSeries[0].data.push(user);
this.usersSeries = [
{
data: this.usersSeries[0].data,
},
];
},
}
const express = require("express");
const app = express();
server = app.listen(11050, function () {
console.log("server is running on port 11050");
});
const io = require("socket.io")(server);
io.on("connection", (socket) => {
console.log("Users component is connected");
socket.on("disconnect", () => {
console.log("Users component was disconnected");
});
setInterval(() => {
socket.emit("newNumber", generateRandomNumber());
}, 1000);
});
function generateRandomNumber() {
let number = Math.floor(Math.random() * 100);
const dateTime = new Date().getTime();
let item = {
x: dateTime,
y: number,
};
return item;
}
Answer the question
In order to leave comments, you need to log in
Donor file:
const express = require("express");
const app = express();
server = app.listen(11050, function () {
console.log("server is running on port 11050");
});
const io = require("socket.io")(server);
io.on("connection", (socket) => {
console.log("Users component is connected");
socket.on("disconnect", () => {
console.log("Users component was disconnected");
});
setInterval(() => {
socket.emit("newNumber", generateRandomNumber());
}, 1000);
});
function generateRandomNumber() {
let number = Math.floor(Math.random() * 100);
const dateTime = new Date().getTime();
let item = {
x: dateTime,
y: number,
};
return item;
}
module.exports = { io };
const { io } = require('путь_к_файлу_донору');
io.on('connection', (socket) => {
// Логика текущего роута
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question