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.iooutside thesocket.on("connection", ()=>{})event.