go_websocket

package module
v0.0.0-...-5769a77 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2023 License: MIT Imports: 12 Imported by: 0

README

go-websocket

基于gorilla/websocket封装的websocket库,实现基于系统纬度的消息推送,基于群组纬度的消息推送,基于单个和多个客户端消息推送。

GoDoc Go Report Card codebeat badge GitHub license

一、目录结构

├── LICENSE
├── README.md
├── client.go           // 客户端
├── client_hub.go       // 客户端集线器
├── code.go             // 状态码
├── example             // 案例
│   └── ws.go
├── go.mod
├── go.sum
├── log.go              // 日志
├── node.go             // 节点(用于在分布式系统生成基于节点的客户端连接ID)
├── response.go         // 客户端发送消息
└── server.go           // 服务

二、在项目中安装使用

go get -u github.com/MQEnergy/go-websocket

三、运行example

1、开启服务
go run examples/ws.go
服务器启动成功,端口号 :9991 

代表启动成功

2、案例

具体查看example目录

1)连接ws并加群组

system_id为系统ID(不必填 不填默认当前节点ip的int值) group_id为群组ID(不必填 不填连接不加群组 注意:群组id为全局唯一ID 不然可能会出现不同系统的相同群组都推送消息)

请求

ws://127.0.0.1:9991/ws?system_id=123&group_id=test

可选多种返回方式 如: Text,Json,Binary(二进制方式) 返回如下json示例:

{
    "code": 0,
    "msg": "客户端连接成功",
    "data": {
        "client_id": "1589962851152388096",
        "group_id": "test",
        "system_id": "123"
    },
    "params": null
}
2)全局广播消息群发

请求

http://127.0.0.1:9991/push_to_system?system_id=123&data={"hello":"world"}

返回

{
    "msg": "系统消息发送成功",
}
3)单个系统消息群发

请求

http://127.0.0.1:9991/push_to_system?system_id=123&data={"hello":"world"}

返回

{
    "msg": "系统消息发送成功",
}
4)推送消息到群组

请求

http://127.0.0.1:9991/push_to_group?system_id=123&group_id=test&data={"hello":"world1"}

返回

{
    "msg": "群组消息发送成功",
}
5)单个客户端消息发送

请求

http://127.0.0.1:9991/push_to_client?client_id=123&data={"hello":"world"}

返回

{
    "msg": "客户端消息发送成功",
}

Documentation

Index

Constants

View Source
const (
	Text MsgType = 1
	Json         = iota + Text
	Binary
)

Variables

View Source
var CodeMap = map[Code]string{
	Success:            "客户端连接成功",
	Failed:             "客户端连接失败",
	ClientFailed:       "客户端主动断连",
	ClientNotExist:     "客户端不存在",
	ClientCloseSuccess: "客户端关闭成功",
	ClientCloseFailed:  "客户端关闭失败",
	ReadMsgErr:         "读取消息体失败",
	ReadMsgSuccess:     "读取消息体成功",
	SendMsgErr:         "发送消息体失败",
	SendMsgSuccess:     "发送消息体成功",
	HeartbeatErr:       "心跳检测失败",
	SystemErr:          "系统不能为空",
	BindGroupSuccess:   "绑定群组成功",
	BindGroupErr:       "绑定群组失败",
	UnAuthed:           "用户未认证",
	InternalErr:        "服务器内部错误",
	RequestMethodErr:   "请求方式错误",
	RequestParamErr:    "请求参数错误",
}
View Source
var (
	Logger *logrus.Logger
)
View Source
var (
	Node *snowflake.Node
)

Functions

func GenerateUuid

func GenerateUuid(node *snowflake.Node) string

GenerateUuid 生成唯一ID

func GetLocalIpToInt

func GetLocalIpToInt() (uint32, error)

GetLocalIpToInt 获取本机IP转成int

func TraceClientCloseFailedLog

func TraceClientCloseFailedLog(params, data, err interface{}, level logrus.Level)

TraceClientCloseFailedLog 客户端关闭失败消息

func TraceClientCloseSuccessLog

func TraceClientCloseSuccessLog(params, data, err interface{}, level logrus.Level)

TraceClientCloseSuccessLog 客户端关闭成功消息

func TraceHeartbeatErrdLog

func TraceHeartbeatErrdLog(params, data, err interface{}, level logrus.Level)

TraceHeartbeatErrdLog 心跳检测失败消息

func TraceLog

func TraceLog(code Code, params, data, err interface{}, level logrus.Level)

TraceLog 写日志

func TraceReadMsgSuccessLog

func TraceReadMsgSuccessLog(params, data interface{}, level logrus.Level)

TraceReadMsgSuccessLog 读取消息体成功消息

func TraceSendMsgErrLog

func TraceSendMsgErrLog(params, data, err interface{}, level logrus.Level)

TraceSendMsgErrLog 发送消息体失败

func TraceSuccessLog

func TraceSuccessLog(params, data interface{}, level logrus.Level)

TraceSuccessLog 客户端连接成功消息

func WriteBindGroupSuccessJson

func WriteBindGroupSuccessJson(conn *websocket.Conn, data, params interface{}) error

WriteBindGroupSuccessJson 返回绑定群组成功

func WriteClientCloseFailedJson

func WriteClientCloseFailedJson(conn *websocket.Conn, data, params interface{}) error

WriteClientCloseFailedJson 返回客户端关闭失败

func WriteClientCloseSuccessJson

func WriteClientCloseSuccessJson(conn *websocket.Conn, data, params interface{}) error

WriteClientCloseSuccessJson 返回客户端关闭成功

func WriteClientFailedJson

func WriteClientFailedJson(conn *websocket.Conn, data, params interface{}) error

WriteClientFailedJson 返回客户端主动断连

func WriteClientNotExistJson

func WriteClientNotExistJson(conn *websocket.Conn, data, params interface{}) error

WriteClientNotExistJson 返回客户端不存在

func WriteFailedJson

func WriteFailedJson(conn *websocket.Conn, data, params interface{}) error

WriteFailedJson 返回客户端连接失败

func WriteHeartbeatErrJson

func WriteHeartbeatErrJson(conn *websocket.Conn, data, params interface{}) error

WriteHeartbeatErrJson 返回心跳检测失败

func WriteJson

func WriteJson(conn *websocket.Conn, code Code, message string, data, params interface{}) error

WriteJson 返回给客户端的信息

func WriteMessage

func WriteMessage(conn *websocket.Conn, code Code, message string, data, params interface{}, msgType MsgType) error

WriteMessage 返回给客户端的信息

func WriteReadMsgErrJson

func WriteReadMsgErrJson(conn *websocket.Conn, data, params interface{}) error

WriteReadMsgErrJson 返回读取消息体失败

func WriteReadMsgSuccessJson

func WriteReadMsgSuccessJson(conn *websocket.Conn, data, params interface{}) error

WriteReadMsgSuccessJson 返回读取消息体成功

func WriteRequestParamErrJson

func WriteRequestParamErrJson(conn *websocket.Conn, data, params interface{}) error

WriteRequestParamErrJson 返回请求参数错误

func WriteSendMsgErrJson

func WriteSendMsgErrJson(conn *websocket.Conn, data, params interface{}) error

WriteSendMsgErrJson 返回发送消息体失败

func WriteSendMsgSuccessJson

func WriteSendMsgSuccessJson(conn *websocket.Conn, data, params interface{}) error

WriteSendMsgSuccessJson 返回发送消息体成功

func WriteSuccessJson

func WriteSuccessJson(conn *websocket.Conn, data, params interface{}) error

WriteSuccessJson 返回客户端连接成功

Types

type BroadcastChan

type BroadcastChan struct {
	Name string `json:"name"`
	Msg  []byte `json:"msg"`
}

type Client

type Client struct {
	ClientId string `json:"client_id"` // 客户端连接ID
	GroupId  string `json:"group_id"`  // 群组id
	SystemId string `json:"system_id"` // 系统ID 为分布式做准备的
	Conn     *websocket.Conn
	// contains filtered or unexported fields
}

func WsServer

func WsServer(hub *Hub, w http.ResponseWriter, r *http.Request, msgtype MsgType) (*Client, error)

WsServer 处理websocket请求

func (*Client) ReadMessageHandler

func (c *Client) ReadMessageHandler()

ReadMessageHandler 将来自 websocket 连接的消息推送到集线器。

func (*Client) WriteMessageHandler

func (c *Client) WriteMessageHandler(msgtype MsgType)

WriteMessageHandler 将消息从集线器发送到 websocket 连接

type Code

type Code int
const (
	Success Code = 0
	Failed  Code = 10001 + iota
	ClientFailed
	ClientNotExist
	ClientCloseSuccess
	ClientCloseFailed
	ReadMsgErr
	ReadMsgSuccess
	SendMsgErr
	SendMsgSuccess
	HeartbeatErr
	SystemErr
	BindGroupSuccess
	BindGroupErr
	UnAuthed
	InternalErr
	RequestMethodErr
	RequestParamErr
)

func (Code) Msg

func (c Code) Msg() string

Msg 返回错误码对应的说明

type Hub

type Hub struct {
	Clients       map[*Client]bool     // 全部客户端列表 {*Client1: bool, *Client2: bool...}
	SystemClients map[string][]*Client // 全部系统列表 {"systemId1": []*Clients{*Client1, *Client2...}, "systemId2": []*Clients{*Client1, *Client2...}}
	GroupClients  map[string][]*Client // 全部群组列表 {"groupId": []*Clients{*Client1, *Client2...}}

	ClientRegister   chan *Client        // 客户端连接处理
	ClientUnregister chan *Client        // 客户端断开连接处理
	ClientLock       sync.RWMutex        // 客户端列表读写锁
	Broadcast        chan []byte         // 来自广播的入站消息
	SystemBroadcast  chan *BroadcastChan // 来自群组的入站消息 {Name:"systemId", Msg:"msg"}
	GroupBroadcast   chan *BroadcastChan // 来自群组的入站消息 {Name:"groupId", Msg:"msg"}
	ClientBroadcast  chan *BroadcastChan // 来自客户端的入站消息 {Name:"clientId", Msg:"msg"}
}

func NewHub

func NewHub() *Hub

NewHub 实例化

func (*Hub) AllBroadcastHandle

func (m *Hub) AllBroadcastHandle(msg []byte)

AllBroadcastHandle 全局广播

func (*Hub) ClientBroadcastHandle

func (m *Hub) ClientBroadcastHandle(clientId string, msg []byte)

ClientBroadcastHandle 单客户端通道处理

func (*Hub) GetGroupClients

func (m *Hub) GetGroupClients(name string) ([]*Client, error)

GetGroupClients 获取群组的客户端列表

func (*Hub) GetSystemClients

func (m *Hub) GetSystemClients(name string) ([]*Client, error)

GetSystemClients 获取系统的客户端列表

func (*Hub) GroupBroadcastHandle

func (m *Hub) GroupBroadcastHandle(groupId string, msg []byte)

GroupBroadcastHandle 群组消息通道处理

func (*Hub) RemoveClientByGroup

func (m *Hub) RemoveClientByGroup(client *Client) error

RemoveClientByGroup 从群组删除客户端

func (*Hub) RemoveGroup

func (m *Hub) RemoveGroup(name string)

RemoveGroup 删除group和群组中的client

func (*Hub) RemoveSystem

func (m *Hub) RemoveSystem(name string)

RemoveSystem 删除system和系统中的client

func (*Hub) Run

func (m *Hub) Run()

Run run chan listener

func (*Hub) SetClientToGroups

func (m *Hub) SetClientToGroups(groupId string, client *Client) bool

SetClientToGroups 添加客户端到分组

func (*Hub) SystemBroadcastHandle

func (m *Hub) SystemBroadcastHandle(systemId string, msg []byte)

SystemBroadcastHandle 系统广播处理

type MsgType

type MsgType int

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL