I create the socket like this in the app.js file:
var express = require('express');
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);
var serverHttps = require('https').createServer({ key: privateKey, cert: certificate }, app);
const socketurl = ['@@socketurl'];
const io = require('socket.io')(server, {
cors: { origin: socketurl },
transports: ['websocket'],
});
io.on('connection', (socket) => {
global.socket = socket
socket.emit('init')
});
.....
exports = module.exports = app;
then, on the server side, in other file (impress.controller.js), I use this socket to emit events like this:
` const waitingOnEmit = global.socket.emitWithAck(‘updateStatusProvaVida’, servidor)
const emitFailed = new Promise(resolve=>{
setTimeout(()=>{
resolve('failed')
},5000)
})
const race = await Promise.race([waitingOnEmit,emitFailed])
if(race == "failed"){
console.error('Error to emit socket: ' + servidor.CPF, error)
....
}
....
On the client side, I listen the event like this:
const socket = io(`${socketurl[0]}`, {
transports:['websocket', 'polling']
});
socket.on('init', () => {
console.log('socket iniciado: ' + socket.id)
})
socket.on('updateStatusProvaVida', (servidor, ackCallBack) => {
ackCallBack({status: 200})
.....
})
For some reason that I can’t understand, sometimes the emit event is fired, like this:
chrome browser log:
enter image description here
Sometimes, the emit event is even fired:
chrome browser log:
enter image description here
Could you help me figure out what am I doing wrong?
Why sometimes the event is fired? Why sometimes the event is not fired?
Thanks in advance!
I tried use ack to check if the listen will get the event, but the point is that the emit event even is fired.
Sabd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.