iT邦幫忙

DAY 8
0

蠻可愛的 Golang系列 第 8

蠻可愛的 golang 8 初探網路程式撰寫

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.

執行的內容頗長,擷取最後一小部份.


上一篇
蠻可愛的 golang 7 Lazy Evaluation
下一篇
一個簡單的 tcp server
系列文
蠻可愛的 Golang30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言