您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何基于Go實(shí)現(xiàn) websocket”,在日常操作中,相信很多人在如何基于Go實(shí)現(xiàn) websocket問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”如何基于Go實(shí)現(xiàn) websocket”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信——允許服務(wù)器主動(dòng)發(fā)送信息給客戶端。
《WebSocket實(shí)現(xiàn)實(shí)時(shí)雙向通信》已經(jīng)介紹java與android如何基于websocket通信。
在golang語(yǔ)言中,目前有兩種比較常用的實(shí)現(xiàn)方式:一個(gè)是golang自帶的庫(kù),另一個(gè)是gorilla,功能強(qiáng)大。
go get github.com/gorilla/websocket
websocket實(shí)現(xiàn)代碼
package gowebsocket import ( "encoding/json" "goweb/common/response" "log" "net/http" "strconv" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) // ClientManager is a websocket manager type ClientManager struct { Clients map[*Client]bool Broadcast chan []byte Register chan *Client Unregister chan *Client } // Client is a websocket client type Client struct { ID int Socket *websocket.Conn Send chan []byte } // Message is return msg type Message struct { Sender string `json:"sender,omitempty"` Recipient string `json:"recipient,omitempty"` Content string `json:"content,omitempty"` } // Manager define a ws server manager var Manager = ClientManager{ Broadcast: make(chan []byte), Register: make(chan *Client), Unregister: make(chan *Client), Clients: make(map[*Client]bool), } //啟動(dòng)websocket服務(wù) // Start is 項(xiàng)目運(yùn)行前, 協(xié)程開(kāi)啟start -> go Manager.Start() func (manager *ClientManager) Start() { for { log.Println("<---管道通信--->") select { case conn := <-Manager.Register: log.Printf("新用戶加入:%v", conn.ID) Manager.Clients[conn] = true jsonMessage, _ := json.Marshal(&Message{Content: "Successful connection to socket service"}) Manager.Send(jsonMessage, conn) case conn := <-Manager.Unregister: log.Printf("用戶離開(kāi):%v", conn.ID) if _, ok := Manager.Clients[conn]; ok { close(conn.Send) delete(Manager.Clients, conn) jsonMessage, _ := json.Marshal(&Message{Content: "A socket has disconnected"}) Manager.Send(jsonMessage, conn) } case message := <-Manager.Broadcast: jsonMessage, _ := json.Marshal(&Message{Content: string(message)}) for conn := range Manager.Clients { select { case conn.Send <- jsonMessage: default: close(conn.Send) delete(Manager.Clients, conn) } } } } } // Send is to send ws message to ws client func (manager *ClientManager) Send(message []byte, ignore *Client) { for conn := range manager.Clients { // if conn != ignore { //向除了自己的socket 用戶發(fā)送 conn.Send <- message // } } } func (c *Client) Read() { defer func() { Manager.Unregister <- c c.Socket.Close() }() for { _, message, err := c.Socket.ReadMessage() if err != nil { Manager.Unregister <- c c.Socket.Close() break } log.Printf("讀取到客戶端的信息:%s", string(message)) Manager.Broadcast <- message } } func (c *Client) Write() { defer func() { c.Socket.Close() }() for { select { case message, ok := <-c.Send: if !ok { c.Socket.WriteMessage(websocket.CloseMessage, []byte{}) return } log.Printf("發(fā)送到到客戶端的信息:%s", string(message)) c.Socket.WriteMessage(websocket.TextMessage, message) } } } // xxx/ws/2 2表示客戶端userId 編號(hào) //WsHandler socket 連接 中間件 作用:升級(jí)協(xié)議,用戶驗(yàn)證,自定義信息等 func WsHandler(c *gin.Context) { userId, err := strconv.Atoi(c.Param("userId")) if err != nil { response.FailResult(http.StatusBadRequest, err.Error(), c) return } conn, err := websocket.Upgrade(c.Writer, c.Request, nil, 1024, 1024) if err != nil { http.NotFound(c.Writer, c.Request) return } //可以添加用戶信息驗(yàn)證 client := &Client{ ID: userId, Socket: conn, Send: make(chan []byte), } Manager.Register <- client go client.Read() go client.Write() }
入口引用
go gowebsocket.Manager.Start() this.GET("/ws/:userId", gowebsocket.WsHandler)
測(cè)試
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .body{text-align: center;} #open{width: 120px;height: 35px;} #close{width: 120px;height: 35px;} #text{display: inline-block;margin: auto;margin-top: 10px;margin-bottom: 10px;width: 240px;} </style> </head> <body class="body"> <button id="open">打開(kāi)連接</button> <button id="close">關(guān)閉連接</button> <br/> <input type="text" name="text" id="text" value="" /> <br/> <button id="send">發(fā)送</button> <div id="msg"> </div> </body> <script> var openbtn = document.getElementById("open") var closebtn = document.getElementById("close") var text = document.getElementById("text") var send = document.getElementById("send") var msg = document.getElementById("msg") var websocket openbtn.onclick = function(){ websocket = new WebSocket("ws://localhost:8080/api/v1/ws/11") websocket.onopen=function(){ console.log("connected"); } websocket.onmessage = function(e){ console.log(e); msg.innerHTML += '<br/>接收:'+e.data; } websocket.onclose=function(e){ console.log("closed",e); } } closebtn.onclick=function(){ websocket.close(1000,"close") } send.onclick=function(){ var msg = text.value websocket.send(msg) } </script> </html>
到此,關(guān)于“如何基于Go實(shí)現(xiàn) websocket”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。