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 {
|
2024-04-16 17:26:37 +08:00
|
|
|
slog.Error(fmt.Sprintf("TCP客户端[rAddr:%s]读取数据异常连接可能断开:", rAddr), opErr)
|
2024-04-13 09:40:25 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
2024-04-16 17:26:37 +08:00
|
|
|
func (c *TcpClient) Send(data []byte) {
|
|
|
|
if c.conn == nil {
|
|
|
|
slog.Error("tcp client send error,conn is nil")
|
|
|
|
return
|
|
|
|
}
|
2024-04-02 18:24:46 +08:00
|
|
|
_, err := c.conn.Write(data)
|
|
|
|
if err != nil {
|
2024-04-16 17:26:37 +08:00
|
|
|
slog.Error("tcp client send error", "error", err)
|
|
|
|
|
2024-04-02 18:24:46 +08:00
|
|
|
}
|
2024-04-16 17:26:37 +08:00
|
|
|
|
2024-04-02 18:24:46 +08:00
|
|
|
}
|