Node.js:socket.io 关闭客户端连接 [英] Node.js: socket.io close client connection

查看:50
本文介绍了Node.js:socket.io 关闭客户端连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何关闭客户端的socket连接?

How can I close the socket connection on the client side?

我正在使用:

  • socket.io 0.9
  • node.js 0.10.15
  • 快递 3.3.4

即:调用 localhost/test
-- 服务端

i.e.: call localhost/test
-- server side

var test = io
.of('/test')
.on('connection', function (socket) {

  console.log('open socket: ' + socket);

  socket.on('disconnect', function () {
    console.log('disconnected event');
    //socket.manager.onClientDisconnect(socket.id); --> endless loop with this disconnect event on server side
    //socket.disconnect(); --> same here
  });
});

-- 客户端

var socket = io.connect('http://localhost:3000/test');
socket.on('disconnect', function () {
   console.log('disconnect client event....');
});

socket.emit('getInitData', function (data) {
  .. do something with data
});

如果我加载测试页面,我需要来自服务器的一些值 (getInitData).
在第一次访问页面时,我获得了一次数据,在重新加载或第二次访问时,我获得了两次数据,依此类推.

If I load the test-page I need some values from the server (getInitData).
On the first page visit I get the data once, on a reload or second visit I get it twice and so on.

服务器端的连接在页面重新加载和离开页面时自动关闭.
但在客户端,连接仍然打开.
如何在客户端关闭连接或检查是否已经有打开的连接?

The connection on the server side is beeing closed automatically on page reload and if you leave the page.
But on the client side the connection is still open.
How can I close the connection on the client side or check if there is already a open connection?

更新
我现在尝试了以下内容:(客户端)

UPDATE
I tried now the following: (client side)

window.onbeforeunload = function(e) {
  socket.disconnect();
};

这会在客户端触发断开连接事件,但我仍然收到两次或三次响应.

This triggers on the client side the disconnect event, but I still get the twice or tripple response.

推荐答案

在服务器端和/或浏览器端没有连接之类的东西.只有一种联系.如果其中一侧关闭它,则它被关闭(并且您不能将数据推送到明显关闭的连接).

There is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed (and you cannot push data to a connection that is closed obviously).

现在浏览器会在您离开页面时关闭连接(它不依赖于您在服务器端使用的库/语言/操作系统).至少对于 WebSockets 来说是这样(由于 keep-alive,长轮询可能不是这样,但希望 socket.io 能够正确处理这个问题).

Now a browser closes the connection when you leave the page (it does not depend on the library/language/OS you are using on the sever-side). This is at least true for WebSockets (it might not be true for long polling because of keep-alive but hopefuly socket.io handles this correctly).

如果发生这样的问题,那么我很确定您自己的代码中存在错误(在服务器端).可能您在不应该的地方堆叠了一些事件处理程序.

If a problem like this happens, then I'm pretty sure that there's a bug in your own code (on the server side). Possibly you are stacking some event handlers where you should not.

这篇关于Node.js:socket.io 关闭客户端连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆