rts-sim-testing-service/third_party/tcp/tcp_client.go

58 lines
1.2 KiB
Go
Raw Normal View History

2024-04-02 18:24:46 +08:00
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
}