Skip to content

Instantly share code, notes, and snippets.

@iwanbk
Created April 3, 2012 20:15
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save iwanbk/2295233 to your computer and use it in GitHub Desktop.
Save iwanbk/2295233 to your computer and use it in GitHub Desktop.
TCP Echo Client in Golang
package main
import (
"net"
"os"
)
func main() {
strEcho := "Halo"
servAddr := "localhost:6666"
tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
if err != nil {
println("ResolveTCPAddr failed:", err.Error())
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
println("Dial failed:", err.Error())
os.Exit(1)
}
_, err = conn.Write([]byte(strEcho))
if err != nil {
println("Write to server failed:", err.Error())
os.Exit(1)
}
println("write to server = ", strEcho)
reply := make([]byte, 1024)
_, err = conn.Read(reply)
if err != nil {
println("Write to server failed:", err.Error())
os.Exit(1)
}
println("reply from server=", string(reply))
conn.Close()
}
@xojoc
Copy link

xojoc commented Feb 5, 2015

I wrote an article on how to write an echo protocol client/server in golang using either udp or tcp: http://xojoc.pw/justcode/golang-echo-protocol.html

@Amirkin
Copy link

Amirkin commented Jan 12, 2016

Thanks, good works!

@g-harel
Copy link

g-harel commented Sep 10, 2018

Is it possible this code will not completely read a response that is longer than 1024 bytes?

@ernierasta
Copy link

@g-harel Yes, look at line 30:
reply := make([]byte, 1024)

@wanglishuang
Copy link

Thank you for sharing, this is helpful for me.

By the way, strEcho := "Halo" may append a \n , otherwise conn.Read will not receive anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment