golang使用 Gin实现 websocket,这里笔者重新搭建一个项目
1、创建项目安装依赖
项目名为 go-gin-websocket
在指定文件夹下,新建项目文件夹 go-gin-websocket
进入项目文件夹,打开cmd窗口,在项目(go-gin-websocket)文件夹路径下,执行初始化命令 go mod init go-gin-websocket
go mod init go-gin-websocket
安装依赖
安装gin
go get -u github.com/gin-gonic/gin
安装websocket
go get github.com/gorilla/websocket
2、搭建项目
在项目目录下新建controller、static、templates、ws文件夹,分别用来存放controller代码、静态文件、页面、websocket代码
在templates目录下新建 index.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello
<script>
var webSocket;
try {
webSocket = new WebSocket('ws://127.0.0.1:8080/ws?id=abc123456789');
}catch (e) {
console.log(e)
}
webSocket.onerror = function(event) {}
//与WebSocket建立连接
webSocket.onopen = function(event) {
console.log('建立连接')
console.log(JSON.stringify(event))
var msg = "身无彩凤双飞翼,心有灵犀一点通"
//发送消息
webSocket.send(msg);
};
//接收服务端发送的消息
webSocket.onmessage=function (m) {
console.log(m)
console.log(m.data)
}
</script>
</body>
</html>
在controller目录下新建 page_controller.go
package controller
import "github.com/gin-gonic/gin"
func Index(c *gin.Context) {
c.HTML(200, "index.html", nil)
}
在ws目录下新建 websocket.go
package ws
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"log"
"net/http"
)
func InitWebSocket(c *gin.Context) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
log.Println("升级协议", r.Header["User-Agent"])
return true
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
userId := c.Query("id")
log.Println("用户id:", userId)
for {
mt, message, err := conn.ReadMessage()
log.Println("获取客户端发送的消息:" + string(message))
fmt.Println(mt)
if err != nil {
log.Println(err)
break
}
var msg = "春风得意马蹄疾,一日看尽长安花"
err2 := conn.WriteMessage(websocket.TextMessage, []byte(msg))
if err2 != nil {
log.Println("write:", err2)
break
}
}
}
在项目根目录下新建 main.go
main.go内容
package main
import (
"github.com/gin-gonic/gin"
"go-gin-websocket/controller"
"go-gin-websocket/ws"
)
func main() {
e := gin.Default()
//html页面位置
e.LoadHTMLGlob("templates/*")
//静态文件位置
e.Static("/static", "./static")
e.GET("/", controller.Index)
e.GET("/ws", ws.InitWebSocket)
e.Run("0.0.0.0:8080")
}
3、运行测试
浏览器请求 http://localhost:8080/
4、添加session
添加session用来存储在线用户
这里使用一个map用来保存,key是用户id,value是websocket连接,再加一个读写锁保证线程安全文章来源:https://www.toymoban.com/news/detail-462591.html
package ws
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"log"
"net/http"
"sync"
)
var connects = make(map[string]*websocket.Conn)
var lock sync.RWMutex
func addSession(id string, conn *websocket.Conn) {
lock.Lock()
connects[id] = conn
defer lock.Unlock()
}
func getSession(id string) *websocket.Conn {
lock.RLock()
defer lock.RUnlock()
return connects[id]
}
func removeSession(id string) {
lock.Lock()
delete(connects, id)
defer lock.Unlock()
}
func InitWebSocket(c *gin.Context) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
log.Println("升级协议", r.Header["User-Agent"])
return true
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
userId := c.Query("id")
log.Println("用户id:", userId)
//添加session
addSession(userId, conn)
for {
mt, message, err := conn.ReadMessage()
log.Println("获取客户端发送的消息:" + string(message))
fmt.Println(mt)
if err != nil {
log.Println(err)
break
}
var msg = "春风得意马蹄疾,一日看尽长安花"
err2 := conn.WriteMessage(websocket.TextMessage, []byte(msg))
if err2 != nil {
log.Println("write:", err2)
break
}
}
}
至此完文章来源地址https://www.toymoban.com/news/detail-462591.html
到了这里,关于golang Gin实现websocket的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!