Connection status
On the client-side, the connected
attribute of the Socket object returns the current state of the connection:
在客户端,Socket对象的connected属性返回连接的当前状态:
1 | import io from 'socket.io-client'; |
Lifecycle diagram
Below is a diagram of the socket lifecycle. It includes the different events emitted by the socket.
下面是套接字生命周期的图表。 它包括套接字发出的不同事件。
Events
This is the list of events that can be emitted by the Socket object.
Event | Description |
---|---|
connect | Fired upon connection (including a successful reconnection) |
disconnect | Fired upon disconnection |
connect_error | Fired upon a connection error |
connect_timeout | Fired upon a connection timeout |
reconnect_attempt | Fired upon an attempt to reconnect |
reconnect_error | Fired upon a reconnection attempt error |
reconnect_failed | Fired when the client couldn’t reconnect within reconnectionAttempts |
reconnecting | Alias for “reconnect_attempt” |
reconnect | Fired upon a successful reconnection |
ping | Fired when a ping is sent to the server |
pong | Fired when a pong is received from the server |
Please note that you can’t reuse those event names in your application:
请注意,您无法在应用程序中重复使用这些事件名称:
1 | socket.emit('reconnect_attempt'); // WARNING: will be silently discarded |
Reconnection(重新连线)
By default, the client will try to reconnect forever.
Here is the default configuration:
默认情况下,客户端将尝试永久重新连接。
这是默认配置:
1 | const socket = io({ |
Delay between two consecutive attempts:
- 1st attempt:
1000 +/- 500 ms
- 2nd attempt:
2000 +/- 1000 ms
- 3nd attempt:
4000 +/- 2000 ms
- following attempts:
5000 +/- 2500 ms
The randomization factor helps smooth the load induced by the reconnection attempts of multiple clients, in case a server goes down.
Sample lifecycle:
两次连续尝试之间的延迟:
第一次尝试:1000 +/- 500毫秒
第二次尝试:2000 +/- 1000毫秒
第三次尝试:4000 +/- 2000毫秒
以下尝试:5000 +/- 2500毫秒
如果服务器发生故障,随机因素有助于平滑由多个客户端的重新连接尝试引起的负载。
样本生命周期:
1 | - connect // the client successfully establishes a connection to the server. |
Example with reconnectionAttempts: 3
:
1 | - connect // the client successfully establishes a connection to the server |
Disabling the default reconnection logic(禁用默认的重新连接逻辑)
Reconnection can be disabled, in case you want to provide your own reconnection logic:
如果您想提供自己的重新连接逻辑,则可以禁用重新连接:
1 | const socket = io({ |
Caught a mistake? Edit this page on GitHub