Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Socket.io Node.js: Creando una instancia de socket.io como una variable

P: ¿Cómo puedo crear una instancia de un socket en node.js usando socket.io ?

Quiero crear una instancia de un socket donde pueda emit eventos fuera del io.on('connection') . Quiero copiar cómo Pusher creó su instancia de pusher para activar eventos del servidor al cliente. Así es como creamos una instancia de empujador:

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

Entonces, lo que quiero con socket.io es crear una instancia de un socket como variable, he intentado devolver la instance de socket desde io.on("connection") pero parece que no funciona.

Este es el código que tengo que está funcionando:

 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__}`); });

Esto es lo que he probado:

 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 Resumen:

¿Hay alguna solución que podamos hacer para desencadenar eventos usando socket.io fuera del socket.on("connection", ()=>{}) .

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!