Skip to content

Fixed failsafeSocket reconnection handling in Chapter 9 state pattern demo code - #14

Open
SafeWinter wants to merge 1 commit into
PacktPublishing:mainfrom
SafeWinter:bug-fixed-ch9-failsafe-socket
Open

Fixed failsafeSocket reconnection handling in Chapter 9 state pattern demo code#14
SafeWinter wants to merge 1 commit into
PacktPublishing:mainfrom
SafeWinter:bug-fixed-ch9-failsafe-socket

Conversation

@SafeWinter

Copy link
Copy Markdown

Description

Fix the failsafeSocket reconnection issue in Chapter 9 state pattern demo code.

When the server process was terminated unexpectedly after a successful connection, the client socket emitted an error event without transitioning back to the offline state. This caused the client process to terminate with an unhandled ECONNRESET error instead of automatically reconnecting and preserving queued messages.

Root Cause

The original implementation only handled connection errors while the socket was in the offline state. Once the connection was established, the socket no longer had a proper error/close handling path to trigger the offline state transition.

As a result, unexpected server-side disconnection did not activate the reconnect workflow.

Here's the screenshot on my PC:

Before:

Client terminates unexpectedly after the server is stopped with Ctrl+C

After:

Multiple clients recover automatically after the server connection is interrupted

Changes

  • Added socket error and close event handling in OnlineState.
  • Destroy and clear the invalid socket instance after connection loss.
  • Transition back to the offline state after the socket is closed, allowing the existing retry mechanism to reconnect automatically.
  • Improved retry timer management in OfflineState to prevent stale reconnect timers from accumulating during repeated connection failures.

Testing

Environment:

  • Node.js v24.9.0

Steps to reproduce the original issue:

  1. Start server.js.
  2. Start client.js.
  3. Wait until messages are successfully received by the server.
  4. Stop the server with Ctrl+C.
  5. Observe the client behavior.

Before the fix:

  • Client terminates with an unhandled ECONNRESET error.

After the fix:

  • Client remains running.
  • Socket transitions back to offline state.
  • Reconnection attempts continue automatically.
  • Queued messages are flushed after the server becomes available again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant