'session' 事件


当新会话或 TLS 票证可用时,则客户端 tls.TLSSocket 上会触发 'session' 事件。 这可能会也可能不会在握手完成之前发生,具体取决于协商的 TLS 协议版本。 该事件未在服务器上触发,或者未创建新会话,例如,当连接恢复时。 对于某些 TLS 协议版本,事件可能会多次发出,在这种情况下,所有会话都可以用于恢复。

在客户端,可以将 session 提供给 tls.connect()session 选项来恢复连接。

请参阅会话恢复了解更多信息。

对于 TLSv1.2 及以下版本,握手完成后可以调用 tls.TLSSocket.getSession()。 对于 TLSv1.3,协议只允许基于票证的恢复,发送多张票证,直到握手完成后才发送票证。 所以需要等待 'session' 事件才能得到可恢复的会话。 应用程序应该使用 'session' 事件而不是 getSession() 来确保它们适用于所有 TLS 版本。 只希望获得或使用一个会话的应用程序应该只监听此事件一次:

tlsSocket.once('session', (session) => {
  // 会话可以立即或稍后使用。
  tls.connect({
    session: session,
    // 其他连接选项...
  });
});

The 'session' event is emitted on a client tls.TLSSocket when a new session or TLS ticket is available. This may or may not be before the handshake is complete, depending on the TLS protocol version that was negotiated. The event is not emitted on the server, or if a new session was not created, for example, when the connection was resumed. For some TLS protocol versions the event may be emitted multiple times, in which case all the sessions can be used for resumption.

On the client, the session can be provided to the session option of tls.connect() to resume the connection.

See Session Resumption for more information.

For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed by the protocol, multiple tickets are sent, and the tickets aren't sent until after the handshake completes. So it is necessary to wait for the 'session' event to get a resumable session. Applications should use the 'session' event instead of getSession() to ensure they will work for all TLS versions. Applications that only expect to get or use one session should listen for this event only once:

tlsSocket.once('session', (session) => {
  // The session can be used immediately or later.
  tls.connect({
    session: session,
    // Other connect options...
  });
});