在建立连接之前发生Socket.io,io.use吗?

时间:2019-08-19 01:18:40

标签: javascript socket.io

我正在使用Socket.io使用函数(https://socket.io/docs/server-api/#namespace-use-fn)对连接进行身份验证,但是我不确定是否可以从该函数中断开套接字,因为我不知道连接是否是在调用“使用”之前完成的。

在建立连接之前,Socket.io是否要等到wp_editor( $post_excerpt, 'post_excerpt', array( 'editor_height' => 50, 'quicktags' => false, 'media_buttons' => false, 'teeny' => true, 'editor_class' => 'post_excerpt' ) ); 完成?如果身份验证失败,如何停止建立连接?

我的测试表明,只有在'use'函数中调用io.use时,才会触发io.on('connection')。但是我还发现,当我在'use'函数中包含next()时,客户端实际上将断开连接,但是服务器仍然认为客户端已连接,如socket.disconnect()所示。 / p>

我已经阅读了这样的问题,它清除了有关“使用”功能的一些细节,但没有解决我的问题:Socket.IO middleware, io.use

io.clients

编辑

通过测试,我基本上找到了答案。 io.use(function (socket, next) { let token = socket.handshake.query.token; if (verify(token) == false) { socket.disconnect(); // Can I do this here? } next(); }); // This isn't fired until the above 'use' function completes, but // despite disconnecting above, 'on connection' still fires and `io.clients` shows the client is connected io.on('connection', function (socket) { setTimeout(function(){ // Get number of connected clients: io.clients((error, clients) => { if (error) throw error; console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD] }); }, 2000); }); 仅在身份验证成功时才能调用。如果失败,请不要调用next(),套接字将无法连接。但是,我不明白为什么在“使用”功能内调用next()会导致服务器认为服务器已连接到客户端,但客户端实际上已断开连接的情况。

0 个答案:

没有答案