The simplest echo server:
Package Mainimport ( "io" "NET" " Log") func main () { Listener, err: = Net. Listen ("TCP", ": 8040") if err! = Nil { log. Fatal (Err) } for { conn, err: = Listener. Accept () if err! = Nil { log. Print (ERR)//e.g., connection aborted continue } go handleconn (conn)//New Goroutines processing connection } }func Handleconn (c net. Conn) { io. Copy (c, c)//Note:ignoring Errors c.close ()}
Principle:
1.io. Copy () method
Func Copy (DST Writer, SRC Reader) (written int64, err error)
2.net.conn type
Type Conn Interface {
Read (b []byte) (n int, err error)
Write (b []byte) (n int, err error)
...
}
A type implements this interface if it has all the required methods for an interface
3.io. Writer
Type Writer Interface {
Write (P []byte) (n int, err error)
}
4.io. Reader
Type Reader Interface {
Read (P []byte) (n int, err error)
}
Upgrade version, each connected to a goroutine, each goroutine a plurality of outputs goroutine
Package Mainimport ("Bufio" "FMT" "Log" "NET" "Strings" "Time") Func main () { Listener, err: = Net. Listen ("TCP", ": 8040") if err! = Nil {log. Fatal (Err)} for {conn, err: = Listener. Accept () if err! = Nil {log. Print (ERR)//e.g., connection aborted continue} Go Handleconn (CO NN)//new goroutines Processing Connection}}func Handleconn (c net. Conn) {input: = Bufio. Newscanner (c) for input. Scan () {go echo (c, input. Text (), 1*time. Second)}//note:ignoring potential errors from input. ERR () c.close ()}func Echo (c net. Conn, shout string, delay time. Duration) {fmt. Fprintln (c, "\ T", strings. ToUpper (Shout)) time. Sleep (delay) fmt. Fprintln (c, "\ T", shout) time. Sleep (delay) fmt. Fprintln (c, "\ T", strings. ToLower (Shout))}
1.fmt. Fprintln ()
Func fprintln (w io. Writer, a ... interface{}) (n int, err error)
2.bufio. Newscanner ()
Func Newscanner (R io. Reader) *scanner
Func (S *scanner) Scan () bool
Func (S *scanner) Text () string
Also used a large number of 7.3 sections to implement the conditions of the interface
Daily Go Language Bible-Example: concurrent echo Service