Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
Socket.io Node.js: Creating an instance of socket.io as a variable

Qn: How can I create an instance of a socket in node.js using socket.io?

I want to create an instance of a socket where i will be able to emit events outside the io.on('connection') listener. I want to copy how Pusher created their pusher instance to trigger events from server to client. Here is how we create a pusher instance:

const Pusher = require("pusher");
const pusher = new Pusher({
....
});
pusher.trigger("my-channel", "my-event", {
  message: "hello world",
});

So what i want with socket.io is to create an instance of a socket as a variable, I have tried to return the socket instance from the io.on("connection") but it seems not working.

This is the code that i have that is working:

import { Server } from "socket.io";
import { createServer, Server as S } from "http";

const server: S = createServer(app);
const io = new Server(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
 });

  io.on("connection", (_socket: any) => {
    console.log("new connection socket.");
    socket.on("disconnect", ()=>console.log("socketid disconnected: ", socket.id))
  });
  server.listen(__port__, () => {
    console.log(`The server is running on port: ${__port__}`);
  });

This is what I've tried:

 const socket:Socket = io.on("connection", (socket: Socket) => socket);
// Now i have returned the socket variable of the current connection
socket.on("disconnect", ()=>console.log("socketid disconnected: ", socket.id)) // this is not working

Qn Summary:

Is there any work around that we can do to trigger events using socket.io outside the socket.on("connection", ()=>{}) event.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda