Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda