The example in this article describes how the go language implements a simple TCP service. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
Package Main
Import (
"NET"
"FMT"
)
var (maxread = 1100
Msgstop = []byte ("Cmdstop")
Msgstart = []byte ("Cmdcontinue")
)
Func Main () {
Hostandport: = "localhost:54321"
Listener: = Initserver (Hostandport)
for {
Conn, err: = Listener. Accept ()
CheckError (Err, "Accept:")
Go Connectionhandler (conn)
}
}
Func initserver (Hostandport string) *net. TcpListener {
SERVERADDR, err: = Net. RESOLVETCPADDR ("TCP", Hostandport)
CheckError (Err, "Resolving Address:port failed: '" + Hostandport + "")
Listener, err: = Net. LISTENTCP ("TCP", SERVERADDR)
CheckError (Err, "LISTENTCP:")
println ("Listening to:", listener. Addr (). String ())
Return listener
}
Func Connectionhandler (Conn net. Conn) {
Connfrom: = conn. Remoteaddr (). String ()
println ("Connection from:", Connfrom)
Talktoclients (conn)
for {
var ibuf []byte = make ([]byte, Maxread + 1)
Length, err: = conn. Read (Ibuf[0:maxread])
Ibuf[maxread] = 0//To prevent overflow
Switch Err {
Case NIL:
Handlemsg (length, err, ibuf)
Default
Goto DISCONNECT
}
}
DISCONNECT:
ERR: = conn. Close ()
println ("Closed connection:", Connfrom)
CheckError (Err, "Close:")
}
Func talktoclients (to net. Conn) {
Wrote, err: = To. Write (Msgstart)
CheckError (Err, "Write:wrote" + string (wrote) + "bytes.")
}
Func handlemsg (length int, err error, MSG []byte) {
If length > 0 {
For I: = 0;; i++ {
If msg[i] = = 0 {
Break
}
}
Fmt. Printf ("Received Data:%v", String (msg[0:length))
Fmt. Println ("Length:", length)
}
}
Func checkerror (Error error, info string) {
If error!= nil {
Panic ("Error:" + info + "" + error.) Error ())//Terminate program
}
}
I hope this article will help you with your go language program.