package test import ( "bufio" "fmt" "net" "testing" "time" ) // TCPServer 定义TCP服务器结构体 type TCPServer struct { ip string port int } // NewTCPServer 构造函数 func NewTCPServer(ip string, port int) *TCPServer { return &TCPServer{ ip: ip, port: port, } } // Start 启动服务器,开始接收数据 func (t *TCPServer) Start() { addr := fmt.Sprintf("%s:%d", t.ip, t.port) // 1. 监听端口 listener, err := net.Listen("tcp", addr) if err != nil { fmt.Printf("❌ 监听失败: %v\n", err) return } defer listener.Close() fmt.Printf("✅ 服务器已启动,监听 %s\n", addr) fmt.Println("📶 等待读写器连接并上报数据...") for { // 2. 阻塞等待客户端(读写器)连接 conn, err := listener.Accept() if err != nil { fmt.Printf("❌ 接受连接失败: %v\n", err) continue } fmt.Printf("🎉 读写器已连接: %s\n", conn.RemoteAddr().String()) fmt.Println("--------------------------------------------------") // 3. 启动协程处理该连接的数据收发 go t.handleConnection(conn) } } // handleConnection 处理单个客户端连接 func (t *TCPServer) handleConnection(conn net.Conn) { defer func() { _ = conn.Close() fmt.Println("❌ 读写器连接断开") }() // 设置读取超时,防止一直阻塞(可选) _ = conn.SetReadDeadline(time.Time{}) reader := bufio.NewReader(conn) buf := make([]byte, 1024) for { // 4. 读取读写器上报的数据 n, err := reader.Read(buf) if err != nil { // 断开连接或读错会退出循环 return } if n > 0 { // 5. 打印原始数据(十六进制格式) data := buf[:n] fmt.Printf("📥 收到原始数据 (Hex): %x\n", data) // 6. 【关键】解析数据 // 根据协议,数据通常包含:帧头 + 长度 + EPC数据 + 校验 // 这里可以添加解析逻辑,例如提取 EPC // if len(data) > 7 { // epcLen := int(data[5]) // 假设第6个字节是长度 // if len(data) >= 6 + epcLen { // epc := data[6 : 6+epcLen] // fmt.Printf("🎯 解析到标签EPC: %x\n", epc) // } // } } } } func TestTCPServer(t *testing.T) { // 启动TCP服务器 fmt.Println("启动TCP服务器...") server := NewTCPServer("192.168.110.218", 9532) server.Start() }