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

68 lines
1.4 KiB
Go
Raw Normal View History

2024-04-02 18:24:46 +08:00
package tcp
import (
2024-04-13 09:40:25 +08:00
"context"
2024-04-02 18:24:46 +08:00
"fmt"
"io"
"log/slog"
"net"
)
type TcpClient struct {
conn *net.TCPConn
handler func(n int, data []byte)
2024-04-13 09:40:25 +08:00
ctx context.CancelFunc
2024-04-02 18:24:46 +08:00
}
2024-04-13 09:40:25 +08:00
func StartTcpClient(rAddr string, handler func(n int, data []byte), readErr func(err error)) (*TcpClient, error) {
2024-04-02 18:24:46 +08:00
raddr, addErr := net.ResolveTCPAddr("tcp", rAddr)
if addErr != nil {
return nil, addErr
}
conn, err := net.DialTCP("tcp", nil, raddr)
2024-04-13 09:40:25 +08:00
ctx, ctxFun := context.WithCancel(context.Background())
2024-04-02 18:24:46 +08:00
if err != nil {
return nil, err
}
go func() {
for {
2024-04-13 09:40:25 +08:00
select {
case <-ctx.Done():
return
default:
}
2024-04-02 18:24:46 +08:00
data := make([]byte, 1024)
l, err := conn.Read(data)
if err != nil {
2024-04-13 09:40:25 +08:00
if opErr, ok := err.(*net.OpError); ok {
slog.Error(fmt.Sprintf("TCP客户端[rAddr:%s]读取数据异常:", rAddr), opErr)
readErr(err)
}
2024-04-02 18:24:46 +08:00
if err == io.EOF {
slog.Warn(fmt.Sprintf("TCP客户端[rAddr:%s]断开连接:", rAddr))
break
}
}
handler(l, data)
}
}()
2024-04-13 09:40:25 +08:00
return &TcpClient{conn: conn, ctx: ctxFun}, nil
2024-04-02 18:24:46 +08:00
}
func (c *TcpClient) Close() {
if c.conn != nil {
2024-04-13 09:40:25 +08:00
slog.Info(fmt.Sprintf("TCP客户端[rAddr:%s]关闭连接", c.conn.RemoteAddr().String()))
c.ctx()
2024-04-02 18:24:46 +08:00
c.conn.Close()
c.conn = nil
}
}
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
}