server.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package server
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/net/gtcp"
  6. "github.com/gogf/gf/os/glog"
  7. gatewayV2 "sparrow-sdk/v2"
  8. )
  9. type Server struct {
  10. closeChan chan struct{}
  11. srv *gtcp.Server
  12. ctx context.Context
  13. addr string
  14. port int
  15. gateWay *gatewayV2.Gateway
  16. }
  17. func NewServer(ctx context.Context, addr string, port int, gw *gatewayV2.Gateway) *Server {
  18. return &Server{
  19. closeChan: make(chan struct{}),
  20. ctx: ctx,
  21. addr: addr,
  22. port: port,
  23. gateWay: gw,
  24. }
  25. }
  26. func (s *Server) Start() error {
  27. glog.Printf("服务端启动[%s:%d]", s.addr, s.port)
  28. srv := gtcp.NewServer(fmt.Sprintf("%s:%d", s.addr, s.port), s.onClientConnect)
  29. s.srv = srv
  30. return s.srv.Run()
  31. }
  32. func (s *Server) Stop() {
  33. s.srv.Close()
  34. }
  35. func (s *Server) onClientConnect(conn *gtcp.Conn) {
  36. glog.Debugf("新的设备接入:%s", conn.RemoteAddr())
  37. client := NewClient(s, conn)
  38. client.closeHandler = func(id string, c *Client) {
  39. glog.Debugf("客户端断开:%s", id)
  40. }
  41. go client.SendLoop()
  42. go client.GetSendByte()
  43. }
  44. func (s *Server) ReportStatus(subId string, data interface{}) error {
  45. return s.gateWay.ReportStatus(subId, "status", data)
  46. }