main.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/url"
  7. "time"
  8. "github.com/gorilla/websocket"
  9. )
  10. // Request 结构体定义
  11. type Request struct {
  12. Type string `json:"type"`
  13. UUID string `json:"uuid"`
  14. CommandID string `json:"commandId"`
  15. Parameter interface{} `json:"parameter"`
  16. }
  17. // Response 结构体定义
  18. type Response struct {
  19. CommandID string `json:"commandId"`
  20. ErrorCode string `json:"errorCode"`
  21. Results map[string]string `json:"results"`
  22. Status string `json:"status"`
  23. Time int64 `json:"time"`
  24. Type string `json:"type"`
  25. UUID string `json:"uuid"`
  26. }
  27. // SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
  28. func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
  29. // 构建WebSocket连接URL
  30. u := url.URL{Scheme: "ws", Host: serverURL, Path: path}
  31. // 创建一个Dialer实例,用于建立WebSocket连接
  32. dialer := websocket.Dialer{
  33. ReadBufferSize: 1024,
  34. WriteBufferSize: 1024,
  35. // 可选:设置超时等
  36. HandshakeTimeout: 5 * time.Second,
  37. }
  38. // 建立WebSocket连接
  39. conn, _, err := dialer.Dial(u.String(), nil)
  40. if err != nil {
  41. return "", fmt.Errorf("dial: %w", err)
  42. }
  43. defer conn.Close()
  44. // 将请求JSON编码为字节
  45. requestJSON, err := json.Marshal(request)
  46. if err != nil {
  47. return "", fmt.Errorf("marshal request: %w", err)
  48. }
  49. // 发送WebSocket消息
  50. err = conn.WriteMessage(websocket.TextMessage, requestJSON)
  51. if err != nil {
  52. return "", fmt.Errorf("write: %w", err)
  53. }
  54. // 读取WebSocket响应
  55. _, responseBytes, err := conn.ReadMessage()
  56. if err != nil {
  57. return "", fmt.Errorf("read: %w", err)
  58. }
  59. // 将响应字节解码为JSON
  60. var response Response
  61. err = json.Unmarshal(responseBytes, &response)
  62. if err != nil {
  63. return "", fmt.Errorf("unmarshal response: %w", err)
  64. }
  65. // 返回sn字段的值
  66. return response.Results["sn"], nil
  67. }
  68. func main() {
  69. // 示例使用
  70. serverURL := "192.168.1.104:9002"
  71. path := "/"
  72. request := Request{
  73. Type: "request",
  74. UUID: "",
  75. CommandID: "getRobotBaseInfo",
  76. Parameter: nil,
  77. }
  78. sn, err := SendWebsocketRequest(serverURL, path, request)
  79. if err != nil {
  80. log.Fatal(err)
  81. }
  82. log.Printf("SN: %s", sn)
  83. }