【问题标题】:Closing a net socket does not cause event on server关闭网络套接字不会导致服务器上的事件
【发布时间】:2017-11-29 06:34:47
【问题描述】:

我正在尝试关闭一个套接字并在服务器上相应地处理该事件。我尝试使用 client.destroy() 和 client.end() 并捕获事件“结束”、“关闭”、“错误”和“超时”,并且没有任何回调被触发。

我用它来杀死套接字:

setTimeout(() => { 
   console.log("destroy"); 
   e._destroyed = true; 
   e._client.end(); 
   e._client.destroy(); 
   logger.debug("Test"); 
}, 1000);

这是我的连接类的构造函数:

constructor(socket, id, onData, onEnd)
{
    this._onDataHandler = onData;
    this._onEndHandler = onEnd;
    this._socket = socket;
    this._socket.setEncoding('UTF-8');
    this._socket.on('data', this._onData.bind(this));
    this._socket.on('end', this._onEnd.bind(this));
    this._socket.on('close', this._onEnd.bind(this));
    this._socket.on('error', this._onEnd.bind(this));
    this._socket.on('timeout', this._onEnd.bind(this));
    this._id = id;
}

这是 onEnd 方法:

_onEnd()
{
    if(this.onEndHandler)
        this._onEndHandler(this);
}

这又应该调用这个:

_onEnd(connection) {
    console.log("Killing connection " + connection);
    let index = this._connections.id;
    this._removeConnection(this._subscriptions, index);
    this._connections[index] = null;
}

这是我得到的输出:

摧毁 [26.05.2017 - 14:05:56] [Timeout.static.main.setTimeout [as _onTimeout] (Core.Main:20:118)] [DEBUG] 测试

仅此而已。因此,除了绑定到所有可能的“连接结束”事件之外,永远不会调用终止连接。这是预期的吗?我在这里错过了一个方法或一些配置吗?或者错误必须在其他地方吗?

PS:客户端上的套接字已关闭,尝试写入它会给出相应的错误。

【问题讨论】:

  • 这可能会有所帮助 (socket.disconnect()):stackoverflow.com/questions/18126677/…
  • 这给了我TypeError: e._client.disconnect is not a function。套接字是通过 net.connect() 创建的,所以它肯定是一个套接字对象。它也没有在官方文档中列出:nodejs.org/api/net.html
  • 哦,我以为你在使用 Socket.io。你有什么理由不使用它?因为它超级简单。
  • 我想使用尽可能少的依赖项,并且由于节点已经有一个网络库,我认为没有理由不使用它。不过,我认为有序地关闭连接应该不是那么难。
  • 你的 onEndHandler 在哪里?好像你有两个 _onEnd 方法?

标签: javascript node.js sockets events


【解决方案1】:

我的代码中有错字:

_onEnd()
{
    if(this.onEndHandler)
        this._onEndHandler(this);
}

if 子句中缺少下划线。现在它按预期工作了。

【讨论】:

    猜你喜欢
    • 2017-08-05
    • 2019-09-10
    • 1970-01-01
    • 2013-02-10
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多