|
|
package client
|
|
|
|
|
|
import (
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
// Client 客户端接口
|
|
|
type Client interface {
|
|
|
// Connect 连接服务器
|
|
|
Connect() error
|
|
|
|
|
|
// Disconnect 断开连接
|
|
|
Disconnect() error
|
|
|
|
|
|
// Send 发送数据
|
|
|
Send(data []byte) error
|
|
|
|
|
|
// Receive 接收数据
|
|
|
Receive() ([]byte, error)
|
|
|
|
|
|
// Request 请求-响应(带超时)
|
|
|
Request(data []byte, timeout time.Duration) ([]byte, error)
|
|
|
|
|
|
// IsConnected 检查是否已连接
|
|
|
IsConnected() bool
|
|
|
|
|
|
// Close 关闭客户端
|
|
|
Close() error
|
|
|
}
|
|
|
|
|
|
// Config 客户端配置
|
|
|
type Config struct {
|
|
|
// 服务器地址(如:tcp://localhost:6995, udp://localhost:6995, ws://localhost:6995等)
|
|
|
Addr string
|
|
|
|
|
|
// 传输层协议(tcp, udp, websocket, unix, serial等)
|
|
|
// 如果指定,将优先使用指定的传输层协议
|
|
|
// 如果为空,将根据Addr前缀自动识别(tcp://, udp://, ws://, wss://, unix://, serial://)
|
|
|
// 如果无法识别,默认使用TCP
|
|
|
TransportProtocol string
|
|
|
|
|
|
// 应用层协议名称(如:nnet、自定义协议等)
|
|
|
// 注意:TCP、UDP、WebSocket是传输层协议,不是应用层协议
|
|
|
// 应用层协议在传输层协议之上运行,用于数据编码/解码
|
|
|
ApplicationProtocol string
|
|
|
|
|
|
// 连接超时时间
|
|
|
ConnectTimeout time.Duration
|
|
|
|
|
|
// 读取超时时间
|
|
|
ReadTimeout time.Duration
|
|
|
|
|
|
// 写入超时时间
|
|
|
WriteTimeout time.Duration
|
|
|
|
|
|
// 是否启用TLS
|
|
|
TLSEnabled bool
|
|
|
|
|
|
// TLS配置
|
|
|
TLS *TLSConfig
|
|
|
|
|
|
// 自动重连
|
|
|
AutoReconnect bool
|
|
|
|
|
|
// 重连间隔
|
|
|
ReconnectInterval time.Duration
|
|
|
|
|
|
// 最大重连次数(0表示无限)
|
|
|
MaxReconnectAttempts int
|
|
|
}
|
|
|
|
|
|
// TLSConfig TLS配置
|
|
|
type TLSConfig struct {
|
|
|
CertFile string
|
|
|
KeyFile string
|
|
|
CAFile string
|
|
|
InsecureSkipVerify bool
|
|
|
}
|
|
|
|
|
|
// DefaultConfig 返回默认配置
|
|
|
func DefaultConfig() *Config {
|
|
|
return &Config{
|
|
|
Addr: "tcp://localhost:6995",
|
|
|
TransportProtocol: "", // 默认根据地址前缀自动识别
|
|
|
ApplicationProtocol: "", // 默认不使用应用层协议(直接使用codec)
|
|
|
ConnectTimeout: 10 * time.Second,
|
|
|
ReadTimeout: 30 * time.Second,
|
|
|
WriteTimeout: 30 * time.Second,
|
|
|
TLSEnabled: false,
|
|
|
AutoReconnect: false,
|
|
|
ReconnectInterval: 5 * time.Second,
|
|
|
MaxReconnectAttempts: 0,
|
|
|
}
|
|
|
}
|