You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.2 KiB
Go
75 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/noahlann/nnet/pkg/nnet"
|
|
)
|
|
|
|
func main() {
|
|
var (
|
|
addr = flag.String("addr", "tcp://127.0.0.1:6995", "Server address")
|
|
protocol = flag.String("protocol", "", "Transport protocol (tcp, udp, websocket, unix, serial). If empty, auto-detect from addr")
|
|
timeout = flag.Duration("timeout", 10*time.Second, "Connection timeout")
|
|
req = flag.String("request", "", "Send a request and wait for response (overrides -message)")
|
|
reqTO = flag.Duration("request-timeout", 2*time.Second, "Request timeout when using -request")
|
|
autoRec = flag.Bool("auto-reconnect", false, "Enable auto reconnect")
|
|
recIntv = flag.Duration("reconnect-interval", 1*time.Second, "Reconnect interval")
|
|
recMax = flag.Int("reconnect-max", 0, "Max reconnect attempts (0 means infinite)")
|
|
message = flag.String("message", "", "Message to send")
|
|
)
|
|
flag.Parse()
|
|
|
|
// 创建客户端配置
|
|
config := &nnet.ClientConfig{
|
|
Addr: *addr,
|
|
TransportProtocol: *protocol, // 如果为空,会根据地址前缀自动识别
|
|
ConnectTimeout: *timeout,
|
|
ReadTimeout: 30 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
AutoReconnect: *autoRec,
|
|
ReconnectInterval: *recIntv,
|
|
MaxReconnectAttempts: *recMax,
|
|
}
|
|
|
|
// 创建客户端
|
|
c := nnet.NewClient(config)
|
|
defer c.Close()
|
|
|
|
// 连接到服务器
|
|
if err := c.Connect(); err != nil {
|
|
fmt.Printf("Failed to connect: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
defer c.Disconnect()
|
|
|
|
// 发送消息
|
|
if *req != "" {
|
|
resp, err := c.Request([]byte(*req), *reqTO)
|
|
if err != nil {
|
|
fmt.Printf("Request error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Response: %s\n", string(resp))
|
|
} else if *message != "" {
|
|
if err := c.Send([]byte(*message)); err != nil {
|
|
fmt.Printf("Failed to send message: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Sent: %s\n", *message)
|
|
|
|
// 接收响应
|
|
response, err := c.Receive()
|
|
if err != nil {
|
|
fmt.Printf("Failed to receive response: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Received: %s\n", string(response))
|
|
} else {
|
|
fmt.Println("Client connected successfully. Use -message to send a message.")
|
|
}
|
|
}
|