GO語言練習:網路編程 TCP 樣本

來源:互聯網
上載者:User

標籤:

1、代碼

2、編譯及運行

 

1、網路編程 TCP 樣本 simplehttp.go 代碼

 1 package main 2  3 import ( 4     "net" 5     "os" 6     "io" 7     "bytes" 8     "fmt" 9 )10 11 func main() {12     if len(os.Args) != 2 {13         fmt.Fprintf(os.Stderr, "Usage : %s host:port", os.Args[0])14         os.Exit(1)15     }16     service := os.Args[1]17     conn, err := net.Dial("tcp", service)18     checkError(err)19 20     _, err = conn.Write([]byte("HEAD / HTTPD/1.0\r\n\r\n"))21     checkError(err)22 23     result, err := readFully(conn)24     checkError(err)25 26     fmt.Println(string(result))27 28     os.Exit(0)29 }30 31 func checkError(err error) {32     if err != nil {33         fmt.Fprintf(os.Stderr, "Fatal error : %s\n", err.Error())34         os.Exit(1)35     }36 }37 38 func readFully(conn net.Conn) ([]byte, error) {39     defer conn.Close()40 41     result := bytes.NewBuffer(nil)42     var buf [512]byte43     for {44         n, err := conn.Read(buf[0:])45         result.Write(buf[0:n])46         if err != nil {47             if err == io.EOF {48                 fmt.Println("over...")49                 break50             }51             return nil, err52         }53     }54 55     return result.Bytes(), nil56 }

2、編譯及運行

  2.1)編譯

$ go build simplehttp.go $ lssimplehttp  simplehttp.go

  2.2)運行

$ ./simplehttp www.xin3e.com:80over...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.19Location: web/index.phpVary: Accept-EncodingConnection: closeContent-Type: text/html

 

GO語言練習:網路編程 TCP 樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.