// client.go SGIP 客户端(Day 33 基础):Bind 登录 + Submit 提交 + Report 接收。 // 无 CMPP 式 ActiveTest 心跳,以读超时/Unbind 判活(基础实现,连接保活由上层通道池负责)。 package sgip import ( "context" "errors" "fmt" "net" "strconv" "sync" "sync/atomic" "time" ) // ErrBindRejected 登录被拒。 var ErrBindRejected = errors.New("sgip: 网关拒绝登录(Bind)") // Config 客户端配置。 type Config struct { Addr string // host:port Name string // 登录名 ≤16B Password string // 密码 ≤16B NodeID uint32 // 本节点 ID(流水号第一段;测试可注入) Timeout time.Duration } // Client SGIP 客户端。 type Client struct { cfg Config mu sync.Mutex conn net.Conn seq atomic.Uint32 pending sync.Map // seq(第 3 段) -> chan uint8(Submit Result) // OnReport 状态报告回调(自动回 ReportResp)。 OnReport func(r *Report) } // NewClient 构造。 func NewClient(cfg Config) *Client { if cfg.Timeout <= 0 { cfg.Timeout = 5 * time.Second } return &Client{cfg: cfg} } // nextSeq 组流水号(node 固定,DateTime=MMDDHHMMSS,Seq 自增)。 func (c *Client) nextSeq() Sequence { dt, _ := strconv.ParseUint(time.Now().Format("0102150405"), 10, 32) return Sequence{NodeID: c.cfg.NodeID, DateTime: uint32(dt), Seq: c.seq.Add(1)} } // Connect 建立 TCP + Bind 握手(Result=0)。 func (c *Client) Connect(ctx context.Context) error { d := net.Dialer{Timeout: c.cfg.Timeout} conn, err := d.DialContext(ctx, "tcp", c.cfg.Addr) if err != nil { return fmt.Errorf("sgip: 连接网关失败: %w", err) } bind := &Bind{Name: c.cfg.Name, Password: c.cfg.Password} s := c.nextSeq() if err := WritePacket(conn, &Header{CommandID: CmdBind, Sequence: s}, bind.Marshal()); err != nil { _ = conn.Close() return err } _ = conn.SetReadDeadline(time.Now().Add(c.cfg.Timeout)) rh, body, err := ReadPacket(conn) _ = conn.SetReadDeadline(time.Time{}) if err != nil { _ = conn.Close() return fmt.Errorf("sgip: 读取 bind_resp 失败: %w", err) } if rh.CommandID != CmdBindResp { _ = conn.Close() return fmt.Errorf("sgip: 期望 bind_resp 实际 cmd=0x%08x", uint32(rh.CommandID)) } result, err := ParseResult(body) if err != nil { _ = conn.Close() return err } if result != 0 { _ = conn.Close() return fmt.Errorf("%w: result=%d", ErrBindRejected, result) } c.mu.Lock() c.conn = conn c.mu.Unlock() go c.readLoop(conn) return nil } // readLoop 读循环:SubmitResp 按 seq 分发;Report → 解析+自动回 ReportResp+回调;Unbind 回应并断开。 func (c *Client) readLoop(conn net.Conn) { for { rh, body, err := ReadPacket(conn) if err != nil { return } switch rh.CommandID { case CmdSubmitResp: result, err := ParseResult(body) if err != nil { continue } if v, ok := c.pending.LoadAndDelete(rh.Sequence.Seq); ok { if ch, ok := v.(chan uint8); ok { select { case ch <- result: default: } } } case CmdReport: rep, err := ParseReport(body) if err != nil { continue } _ = WritePacket(conn, &Header{CommandID: CmdReportResp, Sequence: rh.Sequence}, MakeResultBody(0)) if c.OnReport != nil { c.OnReport(rep) } case CmdUnbind: _ = WritePacket(conn, &Header{CommandID: CmdUnbindResp, Sequence: rh.Sequence}, MakeResultBody(0)) _ = conn.Close() return } } } // Submit 提交并等待 SubmitResp(按流水号第 3 段匹配);返回网关 Result。 func (c *Client) Submit(req *SubmitReq) (uint8, error) { c.mu.Lock() conn := c.conn c.mu.Unlock() if conn == nil { return 0, errors.New("sgip: 未连接") } s := c.nextSeq() ch := make(chan uint8, 1) c.pending.Store(s.Seq, ch) defer c.pending.Delete(s.Seq) if err := WritePacket(conn, &Header{CommandID: CmdSubmit, Sequence: s}, req.Marshal()); err != nil { return 0, fmt.Errorf("sgip: submit 发送失败: %w", err) } select { case result := <-ch: return result, nil case <-time.After(c.cfg.Timeout): return 0, errors.New("sgip: submit_resp 超时") } } // Close 关闭连接。 func (c *Client) Close() error { c.mu.Lock() conn := c.conn c.conn = nil c.mu.Unlock() if conn != nil { return conn.Close() } return nil }