momocow / node-cq-websocket

A Node SDK for developing QQ chatbots based on WebSocket, which is depending on CoolQ and CQHTTP API plugin.

Home Page:https://cq-websocket.js.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

websocket can't be reconnected sometimes

allofee opened this issue · comments

I'm running multiple(more than 5) CQWebsocket instances in my program.

Sometimes one or two instances were not reconnected after reconnect() method called, while other instances did reconnect as expected.

Since there is no internal trace, I've no idea what happened and can only restart my program to restore the connections.

Could you add an "internal trace" feature in the current or next version?
Thanks.

Since this package is a library, which provides APIs, instead of a framework, I don't think loggers are appropriate to be included in a library package. I prefer to emit critical moments via event API.

I'm now preparing the next version (v3), there is one thing I must admit that the state management in v2 is yet far from comprehensive, e.g. the reconnection relies on the underlying WebSocket close event without timeout to take the control back and to finalize the state transition.


After calling reconnect(), there's two decisions according to the CQWebSocket state.

If it is in the CONNECTED state, disconnect() will be called first and the CQWebSocket will wait for a close event from the underlying WebSocket. After the WebSocket is closed, it will then call connect().

If it is in the CLOSED or INIT state, which indicates there is no active connection, it will immediately call connect().

There are several events you can try to listen on during reconnection. You can try to print the state of CQWebSocket instance at both the moment right before calling reconnect() and the moment after calling reconnect(), to see the state transition.

FYI, https://github.com/momocow/node-cq-websocket/blob/v2/src/index.js#L106

console.log(bot._monitor)

Or maybe debug can be used to provide more debug info.

I've listened on the "socket.close", "socket.connecting", "socket.connected", and "socket.ready" events.

All these events not triggered on the abnormal instances when doing a re-connection.

Looks like it is the underlying socket not working correctly.

I'm wondering if you have a workaround for this case?

Many thanks.

Try to listen on socket.closing event, which indicates calling to WebSocket#close() method, and socket.error also. It seems like the underlying socket not being closed as expected.

When the [/api] connection cannot be reconnected, I tried to call the off() method removing all listened events and re-create a CQWebsocket instance which seems to be a workaround.

Easier connection recovery (no matter it's api or event connection) should be taken into consider in the next version.