rts-sim-testing-service/third_party/tcp/tcp_client.go
2024-05-24 09:00:43 +08:00

86 lines
2.0 KiB
Go

package tcp
import (
"context"
"fmt"
"io"
"log/slog"
"net"
)
type TcpClient struct {
conn *net.TCPConn
handler func(n int, data []byte)
ctx context.CancelFunc
conning bool
properties map[string]interface{}
}
func StartTcpClient(rAddr string, properties map[string]interface{}, handler func(n int, data []byte, clientProperties map[string]interface{}), readErr func(err error)) (*TcpClient, error) {
raddr, addErr := net.ResolveTCPAddr("tcp", rAddr)
if addErr != nil {
return nil, addErr
}
conn, err := net.DialTCP("tcp", nil, raddr)
ctx, ctxFun := context.WithCancel(context.Background())
if err != nil {
return nil, err
}
client := &TcpClient{conn: conn, ctx: ctxFun, properties: properties}
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
data := make([]byte, 1024)
l, err := conn.Read(data)
if err != nil {
if opErr, ok := err.(*net.OpError); ok {
slog.Error(fmt.Sprintf("TCP客户端[rAddr:%s]读取数据异常连接可能断开:", rAddr), opErr)
client.conning = false
readErr(err)
}
if err == io.EOF {
slog.Warn(fmt.Sprintf("TCP客户端[rAddr:%s]断开连接:", rAddr))
client.conning = false
readErr(err)
}
}
client.conning = true
handler(l, data, client.properties)
}
}()
client.conning = true
return client, nil
}
func (c *TcpClient) Close() {
if c != nil && c.conn != nil {
slog.Info(fmt.Sprintf("TCP客户端[rAddr:%s]关闭连接", c.conn.RemoteAddr().String()))
c.ctx()
c.conn.Close()
c.conn = nil
}
}
func (c *TcpClient) IsConning() bool {
if c != nil && c.conn != nil {
return c.conning
}
return false
}
func (c *TcpClient) Send(data []byte) error {
if c == nil || c.conn == nil {
slog.Error("tcp client send error,conn is nil")
return fmt.Errorf("TCP未连接车载PC仿真")
}
_, err := c.conn.Write(data)
if err != nil {
slog.Error("tcp client send error", "error", err)
return err
}
return nil
}