您现在的位置是:首页 >其他 >golang Gin实现websocket网站首页其他

golang Gin实现websocket

悟世君子 2023-06-28 20:00:03
简介golang Gin实现websocket

golang使用 Gin实现 websocket,这里笔者重新搭建一个项目

1、创建项目安装依赖

项目名为 go-gin-websocket

在指定文件夹下,新建项目文件夹 go-gin-websocket

d90ea17676bd4ff68ddeb5ecd43845f5.png

进入项目文件夹,打开cmd窗口,在项目(go-gin-websocket)文件夹路径下,执行初始化命令 go mod init go-gin-websocket

go mod init go-gin-websocket

ef282acdb84846dbbaf3c2159feec61c.png

安装依赖

安装gin

go get -u github.com/gin-gonic/gin

 安装websocket

go get github.com/gorilla/websocket

ce9b1f9416f24320a90e01cf7ac8aef2.png

2、搭建项目

在项目目录下新建controller、static、templates、ws文件夹,分别用来存放controller代码、静态文件、页面、websocket代码

05f4bfb81ae94370aa0c7f51b6194ab1.png

在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

243f3a9eeafa4deda10a5bc7c77d3da6.png

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/

1da3a379a25041bfb3861d916c946168.gif

4、添加session

添加session用来存储在线用户

这里使用一个map用来保存,key是用户id,value是websocket连接,再加一个读写锁保证线程安全

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
		}
	}

}

至此完

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。