package server import ( "AT-Server/netAtSDK" "context" "errors" "fmt" "github.com/gogf/gf/container/gmap" "github.com/gogf/gf/net/gtcp" "github.com/gogf/gf/os/glog" ) type Server struct { srv *gtcp.Server ctx context.Context addr string port int clients *gmap.Map } func NewServer(ctx context.Context, addr string, port int) *Server { return &Server{ clients: gmap.New(), ctx: ctx, addr: addr, port: port, } } func (s *Server) Start() error { glog.Printf("服务端启动[%s:%d]", s.addr, s.port) srv := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect) s.srv = srv return s.srv.Run() } func (s *Server) Stop() error { s.clients.Iterator(func(k interface{}, v interface{}) bool { glog.Debugf("客户端:%s,退出", k) client := v.(*Client) client.closeConnection() return true }) return s.srv.Close() } func (s *Server) onClientConnect(conn *gtcp.Conn) { client := NewClient(s, conn) client.closeHandler = func(id string, c *Client) { s.clients.Remove(id) glog.Debugf("客户端下线:%s", id) } client.onReg = func(id string, c *Client) { glog.Debugf("客户端上线:%s", id) s.clients.Set(id, c) } go client.ReadLoop() go client.Test() } // GetATClient 获取AT操作 func (s *Server) GetATClient(imei string) (*netAtSDK.ATClient, error) { if !s.clients.Contains(imei) { return nil, errors.New("客户端不存在:" + imei) } client := s.clients.Get(imei).(*Client) return client.atClient, nil }