Golang NET Package Simulation

Source: Internet
Author: User
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

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.