server.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/container/gmap"
  6. "github.com/gogf/gf/frame/g"
  7. "github.com/gogf/gf/net/gtcp"
  8. "github.com/gogf/gf/os/glog"
  9. gatewayV2 "sparrow-sdk/v2"
  10. "time"
  11. )
  12. type Server struct {
  13. closeChan chan struct{}
  14. srv *gtcp.Server
  15. ctx context.Context
  16. addr string
  17. port int
  18. gateWay *gatewayV2.Gateway
  19. clients *gmap.Map
  20. }
  21. func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway) *Server {
  22. return &Server{
  23. closeChan: make(chan struct{}),
  24. ctx: ctx,
  25. addr: addr,
  26. port: port,
  27. gateWay: gw,
  28. clients: gmap.New(false),
  29. }
  30. }
  31. func (s *Server) Start() error {
  32. glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
  33. srv := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
  34. s.srv = srv
  35. return s.srv.Run()
  36. }
  37. func (s *Server) Stop() {
  38. s.clients.Iterator(func(k interface{}, v interface{}) bool {
  39. client := v.(*Client)
  40. close(client.closeChan)
  41. return true
  42. })
  43. _ = s.srv.Close()
  44. }
  45. func (s *Server) onClientConnect(conn *gtcp.Conn) {
  46. client := NewClient(s, conn)
  47. client.closeHandler = func(id string, c *Client) {
  48. glog.Debugf("客户端断开:%s", id)
  49. if id != "" {
  50. _ = s.gateWay.SubDeviceLogout(g.Cfg().GetString("sparrow.DeviceCode"), id)
  51. s.clients.Remove(id)
  52. }
  53. }
  54. client.regHandler = func(id string, c *Client) {
  55. _ = s.gateWay.SubDeviceLogin(g.Cfg().GetString("Sparrow.DeviceCode"), id)
  56. s.clients.Set(id, c)
  57. }
  58. go client.SendLoop()
  59. time.Sleep(10 * time.Second)
  60. go client.GetSendByte()
  61. }
  62. func (s *Server) ReportStatus(subId string, data interface{}) error {
  63. return s.gateWay.ReportStatus(subId, "status", data)
  64. }
  65. func (s *Server) GetClient(subId string) *Client {
  66. client := s.clients.Get(subId)
  67. if client != nil {
  68. return client.(*Client)
  69. }
  70. return nil
  71. }