package server import ( "AT-Server/netAtSDK" "github.com/gogf/gf/encoding/gbinary" "github.com/gogf/gf/net/gtcp" "github.com/gogf/gf/os/glog" "io" "net" "strings" "sync" "syscall" "time" ) const defaultPassword = "0000" type Client struct { Id string srv *Server conn *gtcp.Conn closeChan chan struct{} closeHandler func(id string, c *Client) onReg func(id string, c *Client) isReg bool mu sync.Mutex waitingATResp bool atClient *netAtSDK.ATClient } func NewClient(s *Server, conn *gtcp.Conn) *Client { return &Client{ srv: s, conn: conn, atClient: netAtSDK.NetATClient(conn, defaultPassword), closeChan: make(chan struct{}), } } func (c *Client) SetId(id string) { c.Id = id } func (c *Client) ReadLoop() { for { select { case <-c.closeChan: return default: buf, err := c.conn.Recv(-1) if err != nil { c.readError(err) glog.Error(c.srv.ctx, err.Error()) return } if len(buf) > 0 { if !c.isReg { id := gbinary.DecodeToString(buf) glog.Debugf("收到注册包!id:%s", id) c.SetId(id) c.isReg = true if c.onReg != nil { c.onReg(c.Id, c) } return } } } } } func (c *Client) readError(err error) { defer c.closeConnection() if err == io.EOF || isErrConnReset(err) { return } glog.Errorf("读取数据发生错误:%s", err.Error()) } func (c *Client) closeConnection() { _ = c.conn.Close() c.conn = nil close(c.closeChan) c.isReg = false if c.closeHandler != nil { c.closeHandler(c.Id, c) } } // isErrConnReset read: connection reset by peer func isErrConnReset(err error) bool { if ne, ok := err.(*net.OpError); ok { return strings.Contains(ne.Err.Error(), syscall.ECONNRESET.Error()) } return false } func (c *Client) send(buf []byte) error { if c.conn == nil { return nil } glog.Debugf("----->%2X", buf) err := c.conn.Send(buf) if err != nil { glog.Error(c.srv.ctx, err) c.closeConnection() return err } return nil } func (c *Client) TestGPS() { for { select { case <-c.closeChan: return default: str, err := c.atClient.GetGPS() if err != nil { glog.Debugf("查询出错:%s", err) continue } glog.Debugf("查询结果 :%s", str) } time.Sleep(10 * time.Second) } }