goProject/trunk/goutil/websocketUtil/websocketUtil.go
皮蛋13361098506 1b77f62820 初始化项目
2025-01-06 16:01:02 +08:00

72 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package websocketUtil
import (
"errors"
"fmt"
"sync"
)
var (
wsmap sync.Map
errLog func(format string, args ...interface{})
debugLog func(format string, args ...interface{})
)
// SetLog
// @Description:设置日志回调函数信息
// @param errLogFun 错误日志回调函数
// @param debugLogFun debug日志回调函数
func SetLog(errLogFun, debugLogFun func(format string, args ...interface{})) {
errLog = errLogFun
debugLog = debugLogFun
}
// Send
// @Description: 发送数据
// @param wsurl 发送地址
// @param st 发送类型使用websocket下的定义
// @param data 发送数据
// @return error
func Send(wsurl string, st int, data []byte) error {
if debugLog == nil || errLog == nil {
return errors.New("websocketUtil未设置errLog,debugLog回调函数请调用websocketUtil.Setlog函数设置相关信息")
}
m, err := getOrAdd(wsurl)
if err != nil {
errLog(fmt.Sprintf("websocketUtil.Send error:%s", err))
return err
}
m.send(st, data)
return nil
}
// getOrAdd
// @Description:获取或者添加对象
// @param url string
// @return *model
// @return error
func getOrAdd(url string) (*model, error) {
var m *model
var err error
v, isOk := wsmap.Load(url)
if isOk {
m = v.(*model)
return m, nil
}
// 不存在创建对应的socket连接
m, err = newModel(url)
if err != nil {
return nil, err
}
// 保存到map
wsmap.Store(url, m)
return m, err
}