Home > Back-end >  when using fmt.Printf() many blanks are displayed
when using fmt.Printf() many blanks are displayed

Time:01-25

I'm trying to complete an echo server using golang. server like this:

// use tcp to echo time
func main() {
    // listen tcp localhost:8000
    listener, err := net.Listen("tcp", "localhost:8000")
    if err != nil {
        fmt.Fprintf(os.Stderr, "listen error, %s", err)
        return
    }
    for {
        // accept
        connection, err := listener.Accept()
        if err != nil {
            fmt.Fprintf(os.Stderr, "listen error, %s\n", err)
        } else {
            handle(connection)
        }
    }
}

// handle the tcp connection
// return the time in one second gap
func handle(connection net.Conn) {
    defer connection.Close()
    for {
        // return written bytes, err
        if _, err := fmt.Fprintf(connection, time.Now().Format("15:04:05\n")); err != nil {
            // write error, probably the client close the connection
            fmt.Fprintf(os.Stderr, "%s close connection\n", connection.RemoteAddr())
            break
        }
        // wait one second
        time.Sleep(1 * time.Second)
    }
}

client like this

package main

const (
    proto = "tcp"
    addr  = "localhost:8000"
)

func main() {
    // client connect to tcp localhost:8000
    connection, err := net.Dial(proto, addr)
    if err != nil {
        fmt.Fprintf(os.Stderr, "connect to %s error, %s", addr, err)
    } else {
        buf := make([]byte, 1024)
        for {
            if _, err := connection.Read(buf); err != nil {
                fmt.Fprintf(os.Stderr, "read from %s error, %s\n", addr, err)
                break
            } else {
                fmt.Printf("data:%s ending\n", buf)
            }
        }
    }

}

when running , the result is : enter image description here

I have no idea why so many blanks are shown. I guess it's probably caused by the built-in function make, but why golang by defalut, displays so many blanks at the end of a string, unlike other high-level languages? Could explain this and fix it?

CodePudding user response:

Read returns n, the number of bytes read. Don't ignore it. Read into a buffer of length cap(buf): buf[:cap(buf)]. Then use n to update the buffer length: buf = buf[:n].

buf := make([]byte, 0, 1024)
for {
    n, err := connection.Read(buf[:cap(buf)])
    buf = buf[:n]
    if err != nil {
        fmt.Fprintf(os.Stderr, "read from %s error, %s\n", addr, err)
        break
    }
    fmt.Printf("data:%s ending\n", buf)
}

CodePudding user response:

You are right, built-in make declare a slice with length and capacity equals to 1024.The better way to deal with such info is to use a protocol which can first read the size of the body, and declare the fit size of the reponse body.

CodePudding user response:

you reserved capacity for byte array that why shown blank, by the way easy way to remove this blank space you can try to use like this

bufString := string(buf)
b := strings.Replace(bufString, "\n", "", 1)
fmt.Printf("data:%s ending\n", b)

please make sure you use "\n" for end of write only

edited (string.Replace() will be clear your blank value in your byte array and convert to string)

  •  Tags:  
  • Related