GO语言练习:网络编程 TCP 示例

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]byte
43     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                 break
50             }
51             return nil, err
52         }
53     }
54 
55     return result.Bytes(), nil
56 }

2、编译及运行

  2.1)编译

$ go build simplehttp.go 
$ ls
simplehttp  simplehttp.go

  2.2)运行

$ ./simplehttp www.xin3e.com:80
over...
HTTP/1.1 302 Found
Date: Mon, 20 Jul 2015 15:18:13 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.3.10-1ubuntu3.19
Location: web/index.php
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

 

你可能感兴趣的:(网络编程)