12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package main
- import (
- "encoding/json"
- "fmt"
- "log"
- "net/url"
- "time"
- "github.com/gorilla/websocket"
- )
- // Request 结构体定义
- type Request struct {
- Type string `json:"type"`
- UUID string `json:"uuid"`
- CommandID string `json:"commandId"`
- Parameter interface{} `json:"parameter"`
- }
- // Response 结构体定义
- type Response struct {
- CommandID string `json:"commandId"`
- ErrorCode string `json:"errorCode"`
- Results map[string]string `json:"results"`
- Status string `json:"status"`
- Time int64 `json:"time"`
- Type string `json:"type"`
- UUID string `json:"uuid"`
- }
- // SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
- func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
- // 构建WebSocket连接URL
- u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
- // 创建一个Dialer实例,用于建立WebSocket连接
- dialer := websocket.Dialer{
- ReadBufferSize: 1024,
- WriteBufferSize: 1024,
- // 可选:设置超时等
- HandshakeTimeout: 5 * time.Second,
- }
- // 建立WebSocket连接
- conn, _, err := dialer.Dial(u.String(), nil)
- if err != nil {
- return "", fmt.Errorf("dial: %w", err)
- }
- defer conn.Close()
- // 将请求JSON编码为字节
- requestJSON, err := json.Marshal(request)
- if err != nil {
- return "", fmt.Errorf("marshal request: %w", err)
- }
- // 发送WebSocket消息
- err = conn.WriteMessage(websocket.TextMessage, requestJSON)
- if err != nil {
- return "", fmt.Errorf("write: %w", err)
- }
- // 读取WebSocket响应
- _, responseBytes, err := conn.ReadMessage()
- if err != nil {
- return "", fmt.Errorf("read: %w", err)
- }
- // 将响应字节解码为JSON
- var response Response
- err = json.Unmarshal(responseBytes, &response)
- if err != nil {
- return "", fmt.Errorf("unmarshal response: %w", err)
- }
- // 返回sn字段的值
- return response.Results["sn"], nil
- }
- func main() {
- // 示例使用
- serverURL := "192.168.1.104:9002"
- path := "/"
- request := Request{
- Type: "request",
- UUID: "",
- CommandID: "getRobotBaseInfo",
- Parameter: nil,
- }
- sn, err := SendWebsocketRequest(serverURL, path, request)
- if err != nil {
- log.Fatal(err)
- }
- log.Printf("SN: %s", sn)
- }
|