Created
April 3, 2012 20:15
-
-
Save iwanbk/2295233 to your computer and use it in GitHub Desktop.
TCP Echo Client in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Thanks, good works!
Is it possible this code will not completely read a response that is longer than 1024 bytes?
@g-harel Yes, look at line 30:
reply := make([]byte, 1024)
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
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