SocketIo.use(function(socket, next)) - 接下来去哪里,如何捕捉或接收它?

SocketIo.use(function(socket, next)) - Where goes next, how to catch or receive it?

我找到了使用 socket.IO 1.* width Express 4 的示例。这是一个 link

一切都很完美。但是有一个密码:

io.use(function(socket, next) {
try {
    var data = socket.handshake || socket.request;
    if (! data.headers.cookie) {
        return next(new Error('Missing cookie headers'));
    }
    console.log('cookie header ( %s )', JSON.stringify(data.headers.cookie));
    var cookies = cookie.parse(data.headers.cookie);
    console.log('cookies parsed ( %s )', JSON.stringify(cookies));
    if (! cookies[COOKIE_NAME]) {
        return next(new Error('Missing cookie ' + COOKIE_NAME));
    }
    var sid = cookieParser.signedCookie(cookies[COOKIE_NAME], COOKIE_SECRET);
    if (! sid) {
        return next(new Error('Cookie signature is not valid'));
    }
    console.log('session ID ( %s )', sid);
    data.sid = sid;
    sessionStore.get(sid, function(err, session) {
        if (err) return next(err);
        if (! session) return next(new Error('session not found'));
        data.session = session;
        next();
    });
} catch (err) {
    console.error(err.stack);
    next(new Error('Internal server error'));
}
});

因此,如果出现错误,它会传递给 next。但是下一步去哪里呢?不用try,catch怎么处理这个错误。我的意思是像快递一样处理下一个接收的地方:

// something here
// And this is callback function which accepts next with err
functin(err, anythingHere){
   if err
      throw err;
   else
      // some code here
}

交给客户。

https://socket.io/docs/server-api/#socket-use-fn

Errors passed to middleware callbacks are sent as special error packets to clients.

io.on('connection', (socket) => {
  socket.use((packet, next) => {
    if (packet.doge === true) return next();
    next(new Error('Not a doge error'));
  });
});

请注意,它后面的任何中间件都不会被调用。

在客户端你可以这样处理:

socket.on('error', function(err){
    // do something with err
});

为了方便再分享一个例子

节点版本:12.13.1 快递 : 4.xx.x 套接字 IO:2.1.1 Socket IO 客户端:2.x.x

io.use((socket, next) => {
  if (
    process.env.NODE_ENV == "production" &&
    socket.handshake.headers.origin != undefined &&
    socket.handshake.headers.origin == config.SOCKET_ORIGIN
  ) {
    return next();
  } else {
    // return next();
    return next(new Error("Invalid Origin"));
  }
})
  .use(async (socket, next) => {
    if (socket.handshake.query.token != undefined) {
      const verificationResponse = await hlpr.JWTVerification(
        socket.handshake.query.token
      );

      if (verificationResponse.err != null) {
        next(new Error("Unauthorized"));
      } else {
        return next();
      }
    } else {
      next(new Error("Unauthorized"));
    }
  })
  .use(async (socket, next) => {
    console.log("*****  socket   ******");
    console.log("*****  next   ******");
    console.log("*****  payload Middlewar Check   ******");
    return next();
  })
  .on("connection", socket => {
      console.log("User Connected Successfully");
  });

客户端代码

const socket = io.connect('ws://xXx.xXx.x.xXx:xxxx', {
          // resource: 'nodejs',
          transport: true,
          query: {token: "xxxXXXxxXXXXXxxxXXXXxxxxXXXXXXXX"}
        });
        socket.on('connect', () => {
          console.log("*******");
          console.log("Successfull Hand Shake");
          console.log("*******");
        }).on('error', (err) => {
          console.log("************ Error ************")
          console.log("************ Error ************")
          console.log(err)
          console.log("************ Error ************")
             // Show the toaster with the error
             // Try re-connect
             // close the socket connection
          });