This is a creation in Article, where the information may have evolved or changed.
Let's make some fun to simulation server-client.
1. Socket
I implement a ECHO server and use Telnet to simulate the socket client.
In the This, we don't need to implement our sockets client but can test our client server in a standard-to-do.
It can support multiple Telnet clients concurrently. The behavior is as bellow.
When user input ' BYE ', the Connect to server shuts down.
Code snippet:
1 Package Main2 3 Import (4 "Bufio"5 "FMT"6 "io"7 "Log"8 "Net"9 "Strings"Ten ) One A Func Main () { - //Listen on TCP Port # on all interfaces. -L, Err: = Net. Listen ("TCP",":") the ifErr! =Nil { - log. Fatal (ERR) - } - defer l.close () + - for { + //Wait for a connection. AConn, Err: =l.accept () at ifErr! =Nil { - log. Fatal (ERR) - } -Fmt. Println ("info:accept a client") - - //Handle the connection in a new goroutine. in go func (c net. Conn) { - defer c.close () to +RD: =Bufio. Newreader (c) - for { theLine, _, Err: =Rd. ReadLine () * ifErr! = Nil && Err! =io. EOF { $ log. Fatal (ERR)Panax Notoginseng } - theS: =string(line) +Fmt. Println ("LOG:", s) A the //since Rd. ReadLine () had trimed last "\ n", append here to echo +_, Err = conn. Write ([]byte("ECHO:"+ S +"\ r \ n")) - ifErr! =Nil { $ log. Fatal (ERR) $ } - - ifStrings. ToLower (s) = ="Bye" { theFmt. Println ("Info:client closed") - BreakWuyi } the } - } (conn) Wu } -}
2. http. Client