// tcp.go
package main
import (
"bytes"
"fmt"
"io"
"net"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage %s host:port", os.Args[0])
os.Exit(1)
}
service := os.Args[1]
conn, err := net.Dial("tcp", service)
checkError(err)
_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
checkError(err)
result, err := readFully(conn)
checkError(err)
fmt.Println(string(result))
fmt.Printf("result len = %d\n", len(result))
os.Exit(0)
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
func readFully(conn net.Conn) ([]byte, error) {
defer conn.Close()
result := bytes.NewBuffer(nil)
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
result.Write(buf[0:n])
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
}
return result.Bytes(), nil
}
输出结果:
C:\Users\Administrator>C:/Go/mycode/20170507/http/http.exe www.oschina.net:80
HTTP/1.1 200 OK
Server: CDN_NWS_4.2.0
Connection: close
Date: Sun, 07 May 2017 10:17:31 GMT
Last-Modified: Mon, 11 Jul 2016 11:18:41 GMT
Content-Type: application/octet-stream
Content-Length: 4096
result len = 206
有疑问加站长微信联系(非本文作者)