diff --git a/third_party/tcp/tcp_client.go b/third_party/tcp/tcp_client.go new file mode 100644 index 0000000..ffeb585 --- /dev/null +++ b/third_party/tcp/tcp_client.go @@ -0,0 +1,57 @@ +package tcp + +import ( + "fmt" + "io" + "log/slog" + "net" +) + +type TcpClient struct { + conn *net.TCPConn + handler func(n int, data []byte) +} + +func StartTcpClient(rAddr string, handler func(n int, data []byte)) (*TcpClient, error) { + raddr, addErr := net.ResolveTCPAddr("tcp", rAddr) + if addErr != nil { + return nil, addErr + } + conn, err := net.DialTCP("tcp", nil, raddr) + + if err != nil { + return nil, err + } + go func() { + for { + data := make([]byte, 1024) + l, err := conn.Read(data) + if err != nil { + if err == io.EOF { + slog.Warn(fmt.Sprintf("TCP客户端[rAddr:%s]断开连接:", rAddr)) + break + } + slog.Error(fmt.Sprintf("TCP客户端[rAddr:%s]读取数据异常:", rAddr), err) + } + handler(l, data) + } + }() + return &TcpClient{conn: conn}, nil +} +func (c *TcpClient) Close() { + if c.conn != nil { + c.conn.Close() + c.conn = nil + slog.Info(fmt.Sprintf("TCP客户端[rAddr:%s]关闭连接", c.conn.RemoteAddr().String())) + } else { + slog.Info(fmt.Sprintf("TCP客户端[rAddr:%s]未连接", c.conn.RemoteAddr().String())) + } +} +func (c *TcpClient) Send(data []byte) error { + _, err := c.conn.Write(data) + if err != nil { + slog.Error("udp client send error", "error", err) + return err + } + return nil +} diff --git a/third_party/tcp/tcp_message.go b/third_party/tcp/tcp_message.go new file mode 100644 index 0000000..887c850 --- /dev/null +++ b/third_party/tcp/tcp_message.go @@ -0,0 +1,14 @@ +package tcp + +type TcpMessageCodec interface { + TcpMessageEncoder + TcpMessageDecoder +} + +type TcpMessageEncoder interface { + Encode() []byte +} + +type TcpMessageDecoder interface { + Decode(data []byte) error +}