Go language exercise: Network Programming TCP Example

Source: Internet
Author: User

1. Code

2. Compiling and Running

1. Network Programming TCP Example Simplehttp.go code

1 Package Main2 3 Import (4     "Net"5     "OS"6     "io"7     "bytes"8     "FMT"9 )Ten  One Func Main () { A     ifLen (OS. Args)! =2 { -Fmt. fprintf (OS. Stderr,"Usage:%s host:port", OS. args[0]) -Os. Exit (1) the     } -Service: = OS. args[1] -Conn, Err: = Net. Dial ("TCP", service) - checkerror (Err) +  -_, Err = conn. Write ([]byte("head/httpd/1.0\r\n\r\n")) + checkerror (Err) A  atresult, err: =readfully (conn) - checkerror (Err) -  -Fmt. Println (string(Result)) -  -Os. Exit (0) in } -  to func checkerror (err error) { +     ifErr! =Nil { -Fmt. fprintf (OS. Stderr,"Fatal Error:%s\n", Err. Error ()) theOs. Exit (1) *     } $ }Panax Notoginseng  -Func readfully (Conn net. Conn) ([]byte, error) { the defer Conn. Close () +  AResult: =bytes. Newbuffer (nil) the     varBUF [ +]byte +      for { -N, err: = conn. Read (buf[0:]) $Result. Write (buf[0: n]) $         ifErr! =Nil { -             ifErr = =io. EOF { -Fmt. Println ("Over ...") the                  Break -             }Wuyi             returnNil, err the         } -     } Wu  -     returnresult. Bytes (), nil About}

2. Compiling and Running

2.1) Compiling

$ go build simplehttp.go $ lssimplehttp  simplehttp.go

2.2) Run

 $./simplehttp www.xin3e.com:80  over ... HTTP /1.1  302   Founddate:mon,  20  Jul 2015  15 : 18 : 13   Gmtserver:apache /2.2 . 22   (Ubuntu) X -powered-by:php/5.3 . 10  -1ubuntu3. 19  location:web /index.phpvary:accept - Span style= "color: #000000;" >encodingconnection:closecontent -type:text/html 

Go language exercise: Network Programming TCP Example

Related Article

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.