简体   繁体   English

无法从发出的事件接收有效载荷 - Socket.io

[英]Can't receive payload from emited event - Socket.io

I have a socket with authentification server which looks like this:我有一个带有身份验证服务器的套接字,如下所示:

const io = require('socket.io').listen(3002);
const jwt = require('jsonwebtoken');

io.use((socket, next) => {
  if (socket.handshake.query && socket.handshake.query.token) {
    jwt.verify(
      socket.handshake.query.token,
      '4-8-15-16-23-42',
      (err, decoded) => {
        if (err) return next(new Error('Authentication error'));
        socket.decoded = decoded;
        next();
      }
    );
  } else {
    next(new Error('Authentication error'));
  }
}).on('connection', socket => {
  socket.emit('connect', 'socket server is connected'); //sending message

  socket.on('recieved', socket => {
    console.log(socket);
  });
});

And the client side looks like this:客户端看起来像这样:

  ...
  useEffect(() => {
    const token = sessionStorage.getItem('token');
    const socket = io('http://localhost:3002', {
      query: { token }
    });

    socket.on('connect', msg => {
      console.log(msg); //undefined
    });
  }, []);
  ...

The problem is that the connection is done but after that when I want to emit another event from my server with some payload, I can't receive the payload on the other side by listening to it.问题是连接已经完成,但是之后当我想从我的服务器发出另一个带有一些有效负载的事件时,我无法通过侦听它来接收另一端的有效负载。

the problem is that the event "connect" you emit is an already "reserved" event that is send from socket server when a socket is successfully connected.问题是您发出的事件“connect”是一个已经“保留”的事件,当套接字成功连接时从套接字服务器发送。

Just do the following change只需做以下更改

Rename the event ex from "connect" to "connected" in both side (client and server) "Server" code在双方(客户端和服务器)“服务器”代码中将事件 ex 从“connect”重命名为“connected”

 socket.emit('connected', 'socket server is connected');

and on the "Client"并在“客户端”上

socket.on('connected', msg => {
  console.log(msg); //msg will no longer be "undefined"
});

and you will be ok你会没事的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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