go_dreamfactory/modules/robot/client.go
2023-08-18 10:37:09 +08:00

68 lines
1.5 KiB
Go

package robot
import (
"go_dreamfactory/lego/sys/log"
"go_dreamfactory/pb"
"sync"
"sync/atomic"
"github.com/gorilla/websocket"
"google.golang.org/protobuf/proto"
)
type Client struct {
sessionId string
uId string
wsConn *websocket.Conn
state int32 //状态 0 关闭 1 运行 2 关闭中
closeSignal chan bool
wg sync.WaitGroup
}
func (this *Client) readLoop() {
defer this.wg.Done()
var (
data []byte
msg *pb.UserMessage = &pb.UserMessage{}
err error
)
locp:
for {
if _, data, err = this.wsConn.ReadMessage(); err != nil {
log.Errorf("agent:%s uId:%s ReadMessage err:%v", this.sessionId, this.uId, err)
go this.Close()
break locp
}
if err = proto.Unmarshal(data, msg); err != nil {
log.Errorf("agent:%s uId:%s Unmarshal err:%v", this.sessionId, this.uId, err)
go this.Close()
break locp
} else {
// this.gateway.Debugf("----------2 agent:%s uId:%s MainType:%s SubType:%s ", this.sessionId, this.uId, msg.MainType, msg.SubType)
if err = this.messageDistribution(msg); err != nil {
break locp
}
}
}
log.Debugf("agent:%s uId:%s readLoop end!", this.sessionId, this.uId)
}
// 外部代用关闭
func (this *Client) Close() {
if !atomic.CompareAndSwapInt32(&this.state, 1, 2) {
return
}
this.wsConn.Close()
this.closeSignal <- true
this.wg.Wait()
atomic.StoreInt32(&this.state, 0)
}
// 分发用户消息
func (this *Client) messageDistribution(msg *pb.UserMessage) (err error) {
return
}