Go language method to implement simple TCP service _golang

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.