So i got my server setup with express with nodejs as follows
index.js
const express = require('express')
const { createServer } = require("http")
const { Server } = require("socket.io")
const app = express()
const socket = require('./controller/socket.js');
// Initialize socket.io
const httpServer = createServer(app)
socket.connect(httpServer);
httpServer.listen(PORT, () => {
console.log(`App listening on port ${PORT}`)
})
And my socket class in socket.js:
let connection = null
class Socket {
constructor() {
this._socket = null
}
connect(httpServer) {
const io = require('socket.io')(httpServer, {
cors: {
origin: "*",
// origin: "http://localhost:8080",
methods: ["GET", "POST"]
}
})
io.on('connection', (socket) => {
this._socket = socket
this._socket.on('statusConnetion',(data) => {
console.log(data,'date')
})
this._socket.on('disconnect', function () {
console.log(socket.id,"disconnect")
})
console.log(`New socket connection: ${socket.id}`)
})
}
emitEvent(event, data) {
console.log('sendFromBackendAll')
this._socket.emit(event, data)
}
registerEvent(event, handler) {
this._socket.on(event, handler)
}
static init(server) {
if(!connection) {
connection = new Socket()
connection.connect(server)
}
}
static getConnection() {
if(!connection) {
throw new Error("no active connection")
}
return connection
}
}
module.exports = {
connect: Socket.init,
connection: Socket.getConnection
}
FRONT_END:
socket.js
import { io } from "socket.io-client";
const URL = "http://localhost:3012";
const socket = io(URL, { autoConnect: true });
and in my vue component i have my listening events:
async created() {
socket.on("backEmit", () => {
console.log('hi)
});
i got two vue clients running. When i start my server both frontend client sockets connects and console prints
New socket connection: WpZ_5__1Kq5x_BHZAAAB
New socket connection: s30YCZ7u1meF_2U4AAAD
When a request is submitted from one client a emit event is triggered to inform the other client to update.
The problem is only one clients listening is working or it is emitting to only one client because,
lets say client 1 and client 2.
When i send request from client 1, the back-end emit is triggered and client 2 hears emit and updates. Now i request from client 2 and back-end emit is triggered but then client 1 does not pick up emit event and does not update.
So only one client hears the event emitted
If anybody can help it would be great
the working client can be #2 sometimes and not #1 depending on who connected first