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 I run my code I get the following result:
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 default, displays so many blanks at the end of a string, unlike other high-level languages? Could explain this and fix it?