diff --git a/websocket/client/client.go b/websocket/client/client.go index 5a02a9d..28f18e9 100644 --- a/websocket/client/client.go +++ b/websocket/client/client.go @@ -32,6 +32,7 @@ func (c *Client) New(session dto.Session) websocket.WebSocket { session: &session, closeChan: make(closeErrorChan, 10), heartBeatTicker: time.NewTicker(60 * time.Second), // 先给一个默认 ticker,在收到 hello 包之后,会 reset + msgHandler: event.ParseAndHandle, } } @@ -44,11 +45,16 @@ type Client struct { user *dto.WSUser closeChan closeErrorChan heartBeatTicker *time.Ticker // 用于维持定时心跳 + msgHandler func(payload *dto.WSPayload) error } type messageChan chan *dto.WSPayload type closeErrorChan chan error +func (c *Client) SetMsgHandler(handler func(payload *dto.WSPayload) error) { + c.msgHandler = handler +} + // Connect 连接到 websocket func (c *Client) Connect() error { if c.session.URL == "" { @@ -218,7 +224,7 @@ func (c *Client) listenMessageAndHandle() { continue } // 解析具体事件,并投递给业务注册的 handler - if err := event.ParseAndHandle(payload); err != nil { + if err := c.msgHandler(payload); err != nil { log.Errorf("%s parseAndHandle failed, %v", c.session, err) } } diff --git a/websocket/iface.go b/websocket/iface.go index 7ab8b7b..9fcd689 100644 --- a/websocket/iface.go +++ b/websocket/iface.go @@ -8,6 +8,8 @@ import ( type WebSocket interface { // New 创建一个新的ws实例,需要传递 session 对象 New(session dto.Session) WebSocket + // SetMsgHandler 设置消息处理回调 + SetMsgHandler(handler func(payload *dto.WSPayload) error) // Connect 连接到 wss 地址 Connect() error // Identify 鉴权连接