这篇文章主要介绍“如何基于Go实现 websocket”,在日常操作中,相信很多人在如何基于Go实现 websocket问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何基于Go实现 websocket”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。
《WebSocket实现实时双向通信》已经介绍java与android如何基于websocket通信。
在golang语言中,目前有两种比较常用的实现方式:一个是golang自带的库,另一个是gorilla,功能强大。
go get github.com/gorilla/websocket
websocket实现代码
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), } //启动websocket服务 // Start is 项目运行前, 协程开启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("用户离开:%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 用户发送 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("发送到到客户端的信息:%s", string(message)) c.Socket.WriteMessage(websocket.TextMessage, message) } } } // xxx/ws/2 2表示客户端userId 编号 //WsHandler socket 连接 中间件 作用:升级协议,用户验证,自定义信息等 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 } //可以添加用户信息验证 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)
测试
<!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">打开连接</button> <button id="close">关闭连接</button> <br/> <input type="text" name="text" id="text" value="" /> <br/> <button id="send">发送</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>
到此,关于“如何基于Go实现 websocket”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。