Browse Source

添加websocket相关功能

master
hreenshan112 10 months ago
parent
commit
c48fe950f6
  1. 39
      controller/common/shiyan.go
  2. 12
      controller/common/type.go
  3. 180
      controller/common/websocketApi.go
  4. 7
      go.mod
  5. 16
      go.sum
  6. 2
      initialization/redis.go
  7. 8
      initialization/router.go
  8. 7
      main.go
  9. 2
      routers/appShiyan/routers.go
  10. 6
      routers/empty.go
  11. 4
      routers/websocketRouters/entry.go
  12. 19
      routers/websocketRouters/router.go

39
controller/common/shiyan.go

@ -263,3 +263,42 @@ func JpgPngToSvg(inputPAgth, outputPath string) {
// fmt.Println("Image converted to SVG successfully.")
}
/*
*
@ 作者: 秦东
@ 时间: 2025-01-07 09:03:07
@ 功能: 访问webservice接口
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) VisitWebserviceInterface(c *gin.Context) {
urlVal_1 := "http://36.134.44.40:9080/ormrpc/services/EASLogin?wsdl"
urlVal_2 := "http://36.134.44.40:9080/ormrpc/services/WSTestFacade?wsdl"
val_1 := generalmethod.CurlGet(urlVal_1)
val_2 := generalmethod.CurlGet(urlVal_2)
sendMap := generalmethod.MapOut[string]()
sendMap["val_1"] = string(val_1)
sendMap["val_2"] = string(val_2)
fmt.Println("======================val_1=======Start===================================")
fmt.Println(string(val_1))
fmt.Println("======================val_2=======Start===================================")
fmt.Println(string(val_2))
fmt.Println("======================val_2=======END===================================")
// formatoutput.Result(0, sendMap, c)
// c.Writer(string(val_1))
c.String(200, string(val_1))
}

12
controller/common/type.go

@ -1,3 +1,15 @@
package common
import (
"sync"
"github.com/gorilla/websocket"
)
type ApiMethod struct{}
// 存储客户端ID和对应的连接
var Clients = make(map[string]*websocket.Conn)
// 设定锁机制
var mutex sync.Mutex

180
controller/common/websocketApi.go

@ -0,0 +1,180 @@
package common
import (
"appNewPlatform/utils/formatoutput"
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
// 定义WebSocket升级器
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
//允许跨域请求
return true
},
}
/*
*
@ 作者: 秦东
@ 时间: 2025-02-12 10:28:36
@ 功能: 测试通讯
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) WsIndex(c *gin.Context) {
//升级HTTP链接为WebSocket连接
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Printf("WebSocket升级失败:%v\n\n", err)
return
}
defer conn.Close()
fmt.Printf("WebSocket升级成功:%v\n\n", err)
for {
messageType, p, err := conn.ReadMessage()
fmt.Printf("messageType:%v\n\n", messageType)
if err != nil {
fmt.Printf("读取消息失败:%v\n\n", err)
break
}
fmt.Printf("收到消息: %v\n\n", string(p))
err = conn.WriteMessage(messageType, p)
if err != nil {
fmt.Printf("发送消息失败:%v\n\n", err)
break
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2025-02-12 11:04:58
@ 功能: 根据用户发送信息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func (a *ApiMethod) IdentityLink(c *gin.Context) {
clientId := c.Query("user_id")
if clientId == "" {
formatoutput.Result(200, "未知人员使用WebSocket!请先表明身份!", c)
return
}
clientId = fmt.Sprintf("user_%v", clientId)
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
formatoutput.Result(200, "WebSocket升级失败:", c)
return
}
defer conn.Close()
//将客户链接添加到存储中
mutex.Lock()
Clients[clientId] = conn
mutex.Unlock()
fmt.Printf("clientId: %v\n\n", clientId)
//信息操作
for {
_, msgCont, err := conn.ReadMessage()
if err != nil {
//客户端断开链接后踢出
mutex.Lock()
delete(Clients, clientId)
mutex.Unlock()
break
}
fmt.Printf("收到消息: %v\n\n", string(msgCont))
receiveMessages(clientId, msgCont)
}
}
/*
*
@ 作者: 秦东
@ 时间: 2025-02-12 11:36:57
@ 功能: 接收消息处理
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func receiveMessages(clientId string, message []byte) {
switch clientId {
case "user_w1":
SendMsgToClient("user_w2", []byte("你好;user_w2"))
break
case "user_w2":
SendMsgToClient("user_w1", []byte("你好;user_w1"))
break
default:
for i, _ := range Clients {
SendMsgToClient(i, message)
}
}
}
/*
*
@ 作者: 秦东
@ 时间: 2025-02-12 11:25:44
@ 功能: 服务端向指定客户发送信息
@ 参数
#
@ 返回值
#
@ 方法原型
#
*/
func SendMsgToClient(clientId string, message []byte) error {
mutex.Lock()
defer mutex.Unlock()
if client, isOk := Clients[clientId]; isOk {
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil { //消息发送失败,说明该链接已经是死链接
client.Close()
delete(Clients, clientId)
return err
}
} else {
errMsg := fmt.Sprintf("未找到客户端ID为 %v 的连接", clientId)
return errors.New(errMsg)
}
return nil
}

7
go.mod

@ -4,11 +4,10 @@ go 1.21.5
require (
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b
github.com/fogleman/gg v1.3.0
github.com/fsnotify/fsnotify v1.7.0
github.com/gin-gonic/gin v1.10.0
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/otiai10/gosseract/v2 v2.4.1
github.com/gorilla/websocket v1.5.3
github.com/redis/go-redis/v9 v9.6.1
github.com/spf13/viper v1.19.0
gorm.io/driver/mysql v1.5.7
@ -16,8 +15,6 @@ require (
)
require (
github.com/Jeffail/gabs v1.4.0 // indirect
github.com/Jeffail/gabs/v2 v2.7.0 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
@ -31,7 +28,6 @@ require (
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
@ -58,7 +54,6 @@ require (
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/image v0.22.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.20.0 // indirect

16
go.sum

@ -1,8 +1,4 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Jeffail/gabs v1.4.0 h1://5fYRRTq1edjfIrQGvdkcd22pkYUrHZ5YC/H2GJVAo=
github.com/Jeffail/gabs v1.4.0/go.mod h1:6xMvQMK4k33lb7GUUpaAPh6nKMmemQeg5d4gn7/bOXc=
github.com/Jeffail/gabs/v2 v2.7.0 h1:Y2edYaTcE8ZpRsR2AtmPu5xQdFDIthFG0jYhu5PY8kg=
github.com/Jeffail/gabs/v2 v2.7.0/go.mod h1:dp5ocw1FvBBQYssgHsG7I1WYsiLRtkUaB1FEtSwvNUw=
github.com/ajstarks/deck v0.0.0-20200831202436-30c9fc6549a9/go.mod h1:JynElWSGnm/4RlzPXRlREEwqTHAN3T56Bv2ITsFT3gY=
github.com/ajstarks/deck/generate v0.0.0-20210309230005-c3f852c02e19/go.mod h1:T13YZdzov6OU0A1+RfKZiZN9ca6VeKdBdyDV+BY97Tk=
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw=
@ -27,8 +23,6 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
@ -53,11 +47,11 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
@ -88,10 +82,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/otiai10/gosseract/v2 v2.4.1 h1:G8AyBpXEeSlcq8TI85LH/pM5SXk8Djy2GEXisgyblRw=
github.com/otiai10/gosseract/v2 v2.4.1/go.mod h1:1gNWP4Hgr2o7yqWfs6r5bZxAatjOIdqWxJLWsTsembk=
github.com/otiai10/mint v1.6.3 h1:87qsV/aw1F5as1eH1zS/yqHY85ANKVMgkDrf9rcxbQs=
github.com/otiai10/mint v1.6.3/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@ -148,8 +138,6 @@ golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/image v0.22.0 h1:UtK5yLUzilVrkjMAZAZ34DXGpASN8i8pj8g+O+yd10g=
golang.org/x/image v0.22.0/go.mod h1:9hPFhljd4zZ1GNSIZJ49sqbp45GKK9t6w+iXvGqZUz4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=

2
initialization/redis.go

@ -26,5 +26,5 @@ func LoadRedis() {
appConstant.CONSTANT_REDIS13 = redisConfig.MasterRedis13.OpenRedis()
appConstant.CONSTANT_REDIS14 = redisConfig.MasterRedis14.OpenRedis()
appConstant.CONSTANT_REDIS15 = redisConfig.MasterRedis15.OpenRedis()
appConstant.CONSTANT_ClusterClient = redisConfig.RedisCluster.OpenRedisColony()
// appConstant.CONSTANT_ClusterClient = redisConfig.RedisCluster.OpenRedisColony()
}

8
initialization/router.go

@ -31,12 +31,16 @@ func InitializeRouter() *gin.Engine {
appLoadRouterGroup.PUT("/", func(c *gin.Context) {
c.JSON(0, "通讯成功!")
})
//实验
shiyanApiRouters := routers.RouterGroupEntry.AppShiyanRouter
{
shiyanApiRouters.RouterGroup(appLoadRouterGroup)
}
//ws通讯
wsApiRouter := routers.RouterGroupEntry.WebSocketRouter
{
wsApiRouter.RouterGroup(appLoadRouterGroup)
}
}
return router
}

7
main.go

@ -2,7 +2,6 @@ package main
import (
"appNewPlatform/appConstant"
"appNewPlatform/controller/common"
"appNewPlatform/initialization"
"fmt"
"runtime"
@ -20,10 +19,10 @@ func main() {
fmt.Printf("设置并发服务器核心数量:%v\n", Ncpu)
runtime.GOMAXPROCS(Ncpu) //设置使用核心数量
inputImagePath := ".\\assets\\img\\1.png" // 替换为实际的输入图像路径,可支持PNG或JPEG
outputSVGPath := "./assets/svg/output_image1111.svg" // 替换为实际的输出SVG路径
// inputImagePath := ".\\assets\\img\\1.png" // 替换为实际的输入图像路径,可支持PNG或JPEG
// outputSVGPath := "./assets/svg/output_image1111.svg" // 替换为实际的输出SVG路径
common.JpgPngToSvgw(inputImagePath, outputSVGPath)
// common.JpgPngToSvgw(inputImagePath, outputSVGPath)
// if err != nil {
// fmt.Println("转换失败:", err)
// } else {

2
routers/appShiyan/routers.go

@ -13,5 +13,7 @@ func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
{
apiRouter.GET("", methodBinding.Index) //入口
apiRouter.POST("", methodBinding.Index) //入口
apiRouter.GET("visitWebserviceInterface", methodBinding.VisitWebserviceInterface) //访问webservice接口
}
}

6
routers/empty.go

@ -1,9 +1,13 @@
package routers
import "appNewPlatform/routers/appShiyan"
import (
"appNewPlatform/routers/appShiyan"
"appNewPlatform/routers/websocketRouters"
)
type RouterGroup struct {
AppShiyanRouter appShiyan.ApiRouter
WebSocketRouter websocketRouters.ApiRouter
}
var RouterGroupEntry = new(RouterGroup)

4
routers/websocketRouters/entry.go

@ -0,0 +1,4 @@
package websocketRouters
//路由
type ApiRouter struct{}

19
routers/websocketRouters/router.go

@ -0,0 +1,19 @@
package websocketRouters
import (
"appNewPlatform/controller"
"github.com/gin-gonic/gin"
)
//ws 路由
func (a *ApiRouter) RouterGroup(router *gin.RouterGroup) {
apiRouter := router.Group("ws")
var methodBinding = controller.ApiInlet.CommonApi
{
apiRouter.GET("", methodBinding.WsIndex) //入口
// apiRouter.POST("", methodBinding.WsIndex) //入口
apiRouter.GET("identity_link", methodBinding.IdentityLink) //根据用户发送信息
}
}
Loading…
Cancel
Save