Golang+Vue實現Websocket全雙工通訊入門

簡介

Websocket是建立在TCP協議之上的應用層協議,HTML5開始,它能夠打通瀏覽器和伺服器之間的通道,形成全雙工通訊, 它複用HTTP的握手通道並與HTTP協議相容,預設埠也是80和443。

場景

Websoket在雲原生領域應用範圍非常廣,比如:

雲平臺透過瀏覽器與K8S中的Pod建立互動式終端通訊

堡壘機,雲平臺等透過瀏覽器,websocket,SSH協議與伺服器建立互動式通訊終端

線上聊天室等

目的

本篇透過Golang與Vue搭建一個基本的Websocket前後端分離快速入門案例,整體架構如下

Golang+Vue實現Websocket全雙工通訊入門

最終打通瀏覽器與服務端的websocket通訊通道

Golang+Vue實現Websocket全雙工通訊入門

詳細實現

首先利用Golang, 開源的Gorilla websocket(https://github。com/gorilla/websocket)實現包,實現ws服務端:

// websockets。gopackage mainimport ( “fmt” “github。com/gorilla/websocket” “net/http”)//協議升級器,將HTTP協議升級為websocket協議,簡稱ws或wss(https)var upgrader = websocket。Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, //允許跨域 CheckOrigin: func(r *http。Request) bool { return true },}func main() { //用http包新建/ws介面, 作為websocket服務端 http。HandleFunc(“/ws”, func(w http。ResponseWriter, r *http。Request) { //呼叫協議升級器的Upgrade方法與前端建立ws連線 conn, err := upgrader。Upgrade(w, r, nil) // error ignored for sake of simplicity if err != nil { fmt。Printf(“[ERROR]:\n%s\n”, err。Error()) return } defer conn。Close() //向客戶端傳送訊息型別為1(標準輸出)的歡迎訊息 if err = conn。WriteMessage(1, []byte(“連線到Websocket服務端成功\r\n”)); err != nil { return } receiveMsg :=“” for { // Read message from browser 從瀏覽器讀取訊息 msgType, msg, err := conn。ReadMessage() if err != nil { fmt。Printf(“[ERROR]從連線中讀取訊息失敗,%+v\n”, err) return } fmt。Printf(“megType:%d, receiveMsg:%s\n”, msgType, receiveMsg) receiveMsg = receiveMsg + string(msg) //拼接訊息,直到遇到回車換行符“\r” fmt。Printf(“%s sent: %s\n”, conn。RemoteAddr(), string(msg)) switch string(msg) { case “\r”: //匹配換行 receiveMsg=“\r\n您的輸入是:”+receiveMsg+“\r\n” if err = conn。WriteMessage(msgType, []byte(receiveMsg)); err != nil { fmt。Printf(“ERROR:%v\n”, err) return } receiveMsg =“” continue } // 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 { fmt。Printf(“ERROR:%v\n”, err) return } } }) http。HandleFunc(“/”, func(w http。ResponseWriter, r *http。Request) { http。ServeFile(w, r, “websockets。html”) }) fmt。Printf(“websockets服務執行中\n”) http。ListenAndServe(“:8081”, nil)}

完成後執行go run main。go,伺服器執行在http://localhost:8081

然後利用前端Vue腳手架工具vue-cli建立前端專案框架,安裝xterm相關元件

建立前端專案vue create websocket安裝xterm相關元件:npm i xterm xterm-addon-fit xterm-addon-attach xterm-addon-web-links

專案整體架構如下:

Golang+Vue實現Websocket全雙工通訊入門

Xtem。js是一個用TypeScript實現的前端元件,可以用瀏覽器為應用提供強大的終端功能

在根元件App。vue元件中,匯入並使用Xtem元件(接下來實現的前端元件)

實現Xtem。vue元件,主要完成終端例項化,繫結前端div,建立websocket並附加到終端,然後就是監聽訊號,完成自適應或者連線關閉的錯誤捕獲,執行回撥方法。

最後執行npm run serve執行前端專案,訪問http://localhost:8080,即可開啟瀏覽器終端客戶端,元件在掛載後自動與後端建立websocket連線,利用該終端就可以與服務端進行互動式通訊。

參考文件

前端元件xterm。js: https://github。com/xtermjs/xterm。js/

GolangWebsocket實現庫之gorilla: https://github。com/gorilla/websocket

END已結束

Golang+Vue實現Websocket全雙工通訊入門

歡迎大家留言, 訂閱, 交流哦!

Golang+Vue實現Websocket全雙工通訊入門

往期回顧

GolangWeb程式設計之控制器方法HandlerFunc與中介軟體Middleware

Golang連線MySQL執行查詢並解析-告別結構體

Golang的一種釋出訂閱模式實現

Golang 併發資料衝突檢測器(Data Race Detector)與併發安全

Golang“驅動”MongoDB-快速入門(“快碼加鞭”)