Stuck At Echo Command, in Golang, not getting response

I don’t know why, I was getting response till concurrent clients, Now suddenly am not getting any response,
Is something wrong in the code?

func main() {
	fmt.Println("Logs from your program will appear here!")

	l, err := net.Listen("tcp", "0.0.0.0:6379")
	if err != nil {
		fmt.Println("Failed to bind to port 6379", err.Error())
		os.Exit(1)
	}

	defer l.Close()
	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Unable to accept the connection", err.Error())
			continue
		}
		go handleConnection(conn)

	}
}

func handleConnection(c net.Conn) {
	defer c.Close()

	reader := bufio.NewReader(c)

	requests := parser(reader)

	if len(requests) < 1 {
		fmt.Println("No requests or Something Wrong with Request Format")
	}

	for i := 0; i < len(requests); i++ {
		subRequest := requests[i]

		currentCommand := subRequest[0]

		if strings.ToUpper(currentCommand) == "ECHO" {
			response := echoHandler(subRequest)
			if response == "" {
				fmt.Println("bad response")
			}
			fmt.Println("response", response)
			_, err := c.Write([]byte(response))

			if err != nil {
				fmt.Println("something went wrong while repsondiong", err.Error())
			}
		}
	}
}

When i hit a request from cli, both server and client terminals were struck.
and when i hit control +c on client side, i am getting all the print statements on the server terminal.
but no response on client side.

@AJAYKE Looks like you’ve got past this stage — do you happen to remember what was wrong? Would love to see if we can improve the tester / instructions.

Hi @andy1li i didn’t pass the stage yet

@AJAYKE Sorry, I misread your original post.

Could you upload your code to GitHub and share the link? It will be much easier to debug if I can run it directly.

I may need to get back to you after the weekend, though.

Is this good?

1 Like

@AJAYKE The issue is with io.Copy:

_, err := io.Copy(&buf, buffer)

io.Copy won’t stop reading until it encounters EOF (i.e. end of connection, in this case), which blocks the server from responding to even the first command.

Consider reading commands one at a time instead, allowing the server to respond to each command as it’s received.

Can you give me sample code example andy?

@AJAYKE Feel free to read this guide:

Hi @andy1li is the testcase wrong? or is my server wrong?

I found the issue,
so earlier, i have been taking input only once for each client connection
but here two clients are sending requests concurrently and multiple commands
But my code is reading it only once, processing it and closing it.
when the second command comes from the first client, the request is closed already.
Now i changed the code to take input in a for loop until it hits end of the file and it solved the issue

thank you

1 Like

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