本文轉自https://www.freeaihub.com/article/websocket-example-in-go.html,該頁可在線運行該實例
本節將使用Go語言 gorilla/websocket 庫在線實現一個基於WebSocket的消息發送的案例,我們將建立一個簡單的服務端用於回播我們向它發送的一切消息。本案例可在線運行,以便於更好的理解go語言的使用以及WebSocket的實際應用。
WebSocket簡介
因為HTTP協議是非持久化的,單向的網絡協議,是不支持長連接的,在建立連接后只允許瀏覽器向服務器發出請求后,服務器才能返回相應的數據。之前要實現實時的通信,采用是下圖左方的輪詢方式,資源消耗非常大。
從HTML5開始提供的一種瀏覽器與服務器進行全雙工通訊的網絡技術,屬於應用層協議。它基於TCP傳輸協議,並復用HTTP的握手通道。
WebSocket簡單的來講,就是可以在瀏覽器里支持雙向通信。
Go語言環境准備
請前往該頁完成安裝后返回本頁進行下一步。
准備gorilla/websocket 庫
go get github.com/gorilla/websocket
WebSocket服務端文件
cd ~
cat > websockets.go << EOF
// websockets.go
package main
import (
"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 simplicity
for {
// Read message from browser
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
// Print the message to the console
fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))
// Write message back to browser
if err = conn.WriteMessage(msgType, msg); err != nil {
return
}
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html")
})
http.ListenAndServe(":80", nil)
}
EOF
WebSocket客戶端文件
cd ~
cat > websockets.html << EOF
<!-- websockets.html -->
<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:80/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.value = "";
}
</script>
EOF
運行驗證
在右側實驗區打開+號下的open vnc
后,在桌面下新建一個終端,運行~/firefox/firefox
,打開FireFox,輸入localhost
即可看到使用的效果。
總結
本節使用Go語言 以及gorilla/websocket 庫實現了一個簡單的ws通訊案例,用戶可以在這個基礎上擴展出功能更為復雜的web應用。