golang有很強大的網路函式庫,我們來看一個
簡單的socket程式範例:
// hello57
package main
import (
"fmt"
"io"
"net"
)
func main() {
var (
host = "ithelp.ithome.com.tw"
port = "80"
remote = host + ":" + port
msg string = "GET / \n"
data = make([]uint8, 4096)
read = true
count = 0
)
// create the socket
con, err := net.Dial("tcp", remote)
// send our message. an HTTP GET request in this case
io.WriteString(con, msg)
// read the response from the webserver
for read {
count, err = con.Read(data)
read = (err == nil)
fmt.Printf(string(data[0:count]))
}
con.Close()
}
使用socket,用 tcp方式要求連線到ithelp,80port.
然後用迴圈一直讀取首頁的內容,列印出來,直到沒有資料時,
跳開,關閉socket.
執行的內容頗長,擷取最後一小部份.