Go的网络编程详解( 四 )

HTTP服务端package mainimport ("fmt""io""net/http")func main() {//resp, _ := http.Get("http://www.baidu.com")//fmt.Println(resp)resp, _ := http.Get("http://127.0.0.1:8000/go")defer resp.Body.Close()// 200 OKfmt.Println(resp.Status)fmt.Println(resp.Header)buf := make([]byte, 1024)for {// 接收服务端信息n, err := resp.Body.Read(buf)if err != nil && err != io.EOF {fmt.Println(err)return} else {fmt.Println("读取完毕")res := string(buf[:n])fmt.Println(res)break}}}六 WebSocket编程webSocket是什么

  • WebSocket是一种在单个TCP连接上进行全双工通信的协议
  • WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据
  • 在WebSocket API中,浏览器和服务器只需要完成一次握手 , 两者之间就直接可以创建持久性的连接,并进行双向数据传输
  • 需要安装第三方包:cmd中:go get -u -v github.com/gorilla/websocket
我们启动一个http服务器,指定根路径路由到一个html页面 , 该页面用来模拟websocket通信的客户端,页面会提供一个按钮触发一段执行websocket通信的js 。服务端接收到websocket请求,然后将请求的内容完整地响应给浏览器 。
接收websocket请求的服务端:
package mainimport ( "fmt" "net/http" "github.com/gorilla/websocket")var upgrader = websocket.Upgrader{ ReadBufferSize:1024, WriteBufferSize: 1024,}func main() { http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicityfor {// Read message from browsermsgType, msg, err := conn.ReadMessage()if err != nil {return}// Print the message to the consolefmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))// Write message back to browserif err = conn.WriteMessage(msgType, msg); err != nil {return}} }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {http.ServeFile(w, r, "H:\\go\\main\\websockets.html") }) http.ListenAndServe(":8080", nil)}发送websocket请求的客户端:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>WebSockets</title></head><body><input id="input" type="text" /><button onclick="send()">Send</button><pre id="output"></pre><script>var input = document.getElementById("input");var output = document.getElementById("output");var socket = new WebSocket("ws://localhost:8080/echo");socket.onopen = function () {output.innerHTML += "Status: Connected\n";};socket.onmessage = function (e) {output.innerHTML += "Server: " + e.data + "\n";};function send() {socket.send(input.value);input.valuehttps://www.huyubaike.com/biancheng/= "";}</script></body></html>

推荐阅读