golang中使用websocket簡單示例
阿新 • • 發佈:2019-02-07
首先匯入需要用到的工具包:
go get github.com/gobwas/ws/wsutil
go get github.com/gobwas/ws/
服務端程式碼示例:
web.go
package main import ( "fmt" "io" "log" "net" "net/http" "github.com/gobwas/ws/wsutil" "github.com/gobwas/ws" ) var n net.Conn func web(w http.ResponseWriter, r *http.Request) { conn, _, _, err := ws.UpgradeHTTP(r, w, nil) if err != nil { log.Println("連線失敗:", err) } for { defer conn.Close() var ( state = ws.StateServerSide reader = wsutil.NewReader(conn, state)//建立一個讀取器,從conn中讀取狀態以保持連線 writer = wsutil.NewWriter(conn, state, ws.OpText)//建立一個新的快取資料區,ws.OpText是操作碼 ) header, _ := reader.NextFrame()//讀取conn中的下一條資料 writer.Reset(conn, state, header.OpCode)//重置緩衝資料區,並給其制定新的操作碼 if _, err := io.Copy(writer, reader); err != nil {//將讀取到的資料copy到writer fmt.Println("copy err :", err) } if err := writer.Flush(); err != nil {//Flush將所有緩衝資料寫入底層的io.Writer(傳送給客戶端) fmt.Println("Flush err :", err) } } } func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "static/web.html") }) http.HandleFunc("/ws", web) http.ListenAndServe(":1234", nil) }
客戶端程式碼:
web.html
<!-- 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:1234/ws"); 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>
訪問路徑:
效果如圖: