简体   繁体   中英

Socket.io Client connects, socket.on events don't fire

I'm using the package "socket.io-client": "^2.2.0"

In my web app I have the following code on bootstrap:

export const socket = io.connect(process.env.VUE_APP_SOCKET_URL, {
  reconnection: true,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  reconnectionAttempts: Infinity
})

Then later in the app cycle I have the following listener

import socket from './api/socket'

function handleAutobox() {
  console.log('handling autobox')
}
console.log('Connect')
socket.on('autobox', handleAutobox)

When inspecting in production, I see that the code has run ('Connect' is logged). I see that the socket network traffic is captured:

在此处输入图片说明

The problem is the handleAutobox function is never called. If I'm sure I've run socket.on, how is that possible?

UPDATE: ADDING SERVER SIDE CODE:

let socket_io = require('socket.io'),
    io;

let server = http.createServer(app)
  .listen(app.get('port'), () => {
    io = socket_io.listen(server);
    console.info(`App listening on port ${port}!`);
  });

// ...inside route function:
io.emit('autobox', autobox);

UPDATE: ADDING socket.on('connect' ...) :

When adding socket.on('connect' ...) directly after creating the socket, I am finding that doesn't get called either. Instead of io.connect(...) I tried @Keith's suggestion of io() with separate io.on events, still no dice.

So the real problem is that no "connection" is being made but data is still being sent on the network. I guess I'm really not understanding something about sockets. Apparently data can be sent even though no connection is established?

It looks like your console.log('Connect') is global so it will run no matter what. try putting it in your a function that calls when socket is connected. so on your server do you have something like

io.on('connection' function(socket) {
  console.log('Socket Connected');
// Update
io.emit('autobox', autobox);
  socket.emit('autobox');
})

U can not place socket code inside of routes it has to be inside this connection callback and this callback only. At least thats what I have been told. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM