P
P
postya2020-11-08 08:21:13
Socket.io
postya, 2020-11-08 08:21:13

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,
        },
      ];
    },
  }


In express, all methods are written in one 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;
}


Expected result:
In vue js, a specific path is written in each component, and only methods of a specific route are listened for
const socket = io(" localhost:11050/users ");

In express, somehow you need to create a file and move methods from a common file to a file only for a specific route.

How can this be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-11-08
@postya

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 };

Descendant file:
const { io } = require('путь_к_файлу_донору');

io.on('connection', (socket) => {

   // Логика текущего роута

})

And if you want app.post('/socketRoute') - then read the socket documentation, everything about the rooms is chewed to the smallest detail, you will hang empty routes in the express like => app.post('/needFuckingSocketRoom', (req, res ) => {}); and already open a socket connection of a certain room after a request for this route, this is a crutch as for me, I didn’t delve into this deeply

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question