1

I'm using Express with Socket.io but I can't figure out how to use SocKet.io in Express routes and server.js at the same time.

This is my app.js

import http from "http";
import io from "socket.io";
import express from "express";
import path from "path";
import bodyParser from "body-parser";
import cors from "cors";

import routes from "./routes";


class App {
  constructor() {
    this.server = express();
    this.middlewares();
    this.routes();
    this.serverHttp = http.createServer(this.server);
    this.io = io.listen(this.serverHttp);
  }

  middlewares() {
    this.server.use(express.json());
    this.server.use(
      bodyParser.urlencoded({ extended: false })
    );
    this.server.use(bodyParser.json());
    this.server.use(cors());

    this.io.on("connection", socket => {
      console.log("Connected");
    });

    this.server.use((req, res, next) => {
      req.io = this.io;

      next();
    });
  }

  routes() {
    this.server.use(routes);
  }
}

export default new App().serverHttp;


And the file below is my server.js


import app from "./app";

const port = process.env.PORT;
const hostname = process.env.HOST;

app.listen(port, "0.0.0.0");

When I try it in the way above the client side don`t comunicate with the server side.

I managed to make it work putting everything in the server.js, just like the snippet below. But I need the io in the request to use the method emit.

import http from "http";
import io from "socket.io";

import app from "./app";

const port = process.env.PORT;
const hostname = process.env.HOST;

const http2 = http.Server(app);

const socket = io(http2);

socket.on("connection", socket => {
  console.log("Connected");
});

http2.listen(port, "0.0.0.0");

  • This is a lot of words and code, but if all you're trying to do is to send a socket.io message to the same client that is making an http request to your server in an express route handler, then you can see how to set that up here: https://stackoverflow.com/questions/42379952/combine-sockets-and-express-when-using-express-middleware/42380682#42380682. If your goal is something else, please clarify. – jfriend00 Apr 07 '20 at 18:19
  • Basically, I need to start the server, and pass the socket.io configuration through request. – Mateus Moreira Apr 07 '20 at 19:29
  • Sorry, still don't understand what you're actually trying to accomplish. Your previous comment sounds like a possible solution to something, not the actual problem. Please describe the actual problem. I want to do X. What is X? – jfriend00 Apr 07 '20 at 19:32
  • The first piece of code that is my problem, there I start socket.io, and export it to server.js (the second piece of code). But the client side can't connect that way, and I don't know why. The third piece of code, was to show, that in a single file there is communication, but I can't pass the socket through the request. – Mateus Moreira Apr 07 '20 at 19:46

0 Answers0