Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a TCP and UDP Client and Server using Go Proposed Changes #3388

Open
ghost opened this issue Jun 8, 2020 · 0 comments
Open

Create a TCP and UDP Client and Server using Go Proposed Changes #3388

ghost opened this issue Jun 8, 2020 · 0 comments

Comments

@ghost
Copy link

ghost commented Jun 8, 2020

Link: https://linode.com/docs/development/go/developing-udp-and-tcp-clients-and-servers-in-go/

Issue

The example programs create and discard bufio.Readers in inner loops. Any data buffered in the bufio.Reader is also discarded. The discarded data may not be an issue in your tests cases, but people are copying your code to their own applications where things break.

This error is common in network programming questions on StackOverflow. I suspect that many of the questioners are getting their code from this page.

Suggested Fix

Change code like this:

   for {
            reader := bufio.NewReader(os.Stdin)
            fmt.Print(">> ")
            text, _ := reader.ReadString('\n')
            fmt.Fprintf(c, text+"\n")

            message, _ := bufio.NewReader(c).ReadString('\n')
            fmt.Print("->: " + message)
            if strings.TrimSpace(string(text)) == "STOP" {
                    fmt.Println("TCP client exiting...")
                    return
            }
    }

To

   inReader := bufio.NewReader(os.Stdin)
   cReader := bufio.NewReader(c)
   for {
            fmt.Print(">> ")
            text, _ := inReader.ReadString('\n')
            fmt.Fprintf(c, text+"\n")

            message, _ := cReader.ReadString('\n')
            fmt.Print("->: " + message)
            if strings.TrimSpace(string(text)) == "STOP" {
                    fmt.Println("TCP client exiting...")
                    return
            }
    }

All uses of bufio.NewReader in the example programs have this problem. Fix all of them.

Hall of Shame (SO questions that follow the bad advice in the Linode article):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants