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