Keep getting "connection refused" for #EJ5

Hello!

My test keeps showing the “connection refused” message. It was working for the first few attempts I had with this challenge, but then it started giving me the same error even though I reverted back my code to an older version (following this).

The commit reverted back to is 0fbbc58, which I expected to see “Expected connection to stay open, but it is close” like the first time, but now I continue to see the connection refused.

I noticed that I was on VPN at one point, not sure if that was the issue, but I’m disconnected now and still getting this error.

remote: [tester::#EJ5] Running tests for Stage #EJ5 (Concurrent connections)
remote: [tester::#EJ5] Running program
remote: [tester::#EJ5] $ ./your_program.sh
remote: [tester::#EJ5] Creating 2 parallel connections
remote: [tester::#EJ5] Creating connection 1
remote: [tester::#EJ5] Creating connection 2
remote: [tester::#EJ5] dial tcp [::1]:4221: connect: connection refused
remote: [tester::#EJ5] Test failed
remote: [tester::#EJ5] Terminating program
remote: [tester::#EJ5] Program terminated successfully

Here’s my code: Codecrafters EJ5 · GitHub

I also ran sudo lsof -i -n -P | grep 4221 and don’t see any process using port 4221.

Hey @macaw-805, there might be a few things going on. The first two I noticed are:

  1. defer con.Close() will run when main() returns. This means the connection can close before the handler does anything.

  2. go handler(con) starts a goroutine but doesn’t block, so main() exits immediately.

To fix this, you can introduce an infinite loop so l.Accept() keeps waiting for new connections and your handler has time to do its job:

func main() {
    ...

	for {
		// Blocks until a client connects, then returns a connection object.
		// It handles a single connection before exiting.
		con, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting connection: ", err.Error())
			os.Exit(1)
		}

		// Handle concurrent connections.
		go handler(con)
	}
}

Let me know if you’d like further clarification!

Thank you very much for the help and explanation! That solved my issue.

On a separate note, what is that wonderful font you are using? It’s beautiful!

1 Like

Oh, it’s a paid font called Operator Mono.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.