123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- 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
- sendChan chan []byte
- }
- 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)
- 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) Test() {
- time.Sleep(60 * time.Second)
- str, err := c.atClient.GetAll()
- if err != nil {
- glog.Debugf("查询出错:%s", err)
- }
- glog.Debugf("查询结果 :%s", str)
- }
|