duanhong8839 2017-10-05 10:15
浏览 1044
已采纳

Golang WebSocket客户端,获取结果后关闭连接

How I can implement this kind of scenario:

1.I have LoginHandler which receives some user data - email and signedXml:

func LoginHandler(c *gin.Context) {
    var (
        err  error
        data LoginPost
    )
    if err = c.BindJSON(&data); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"status": "error"})
        return
    }

    ...

    c.JSON(http.StatusOK, gin.H{"status": "ok"})
}

2.I need to send signedXml to another server via websocket

3.Save result (success or error)

4.Close connection

Every HTTP request will open connection, send 1 message, get 1 result and finally close socket. I was trying with channel, but no success. Is this possible to implement my case?

UPDATE

package main

import (
    "log"
    "net/url"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
    "net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
    message := r.FormValue("message")
    w.Write([]byte(message))
}

func postHandler(w http.ResponseWriter, r *http.Request) {
    var (
        message = r.FormValue("message")
        u = url.URL{Scheme: "ws", Host: "echo.websocket.org", Path: "/"}
        err error
        out []byte
        conn *websocket.Conn
    )
    log.Printf("message: %s
", message)
    log.Printf("connecting to %s
", u.String())
    conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    log.Println("write")
    if err = conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
        log.Fatal("write:", err)
    }
    log.Println("read")
    if _, out, err = conn.ReadMessage(); err != nil {
        log.Fatal("read:", err)
    }
    w.Write(out)
    log.Println("close")
    conn.Close()
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", indexHandler).Methods("GET")
    r.HandleFunc("/post", postHandler).Methods("POST")
    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}
  • 写回答

1条回答 默认 最新

  • dpp78272 2017-10-05 15:42
    关注

    Call Dial, WriteMessage, ReadMessage and Close in sequence.

    c, _, err := websocket.DefaultDialer.Dial(url, nil)
    if err != nil {
        // handle error
    }
    err := c.WriteMessage(websocket.TextMessage, signedXML)
    if err != nil {
         // handle error
    }
    _, p, err := c.ReadMessage()
    if err != nil {
         // handle error
    }
    c.Close()
    
    // p is a []byte with the first received message.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥30 logisim中设计一个位于十字路口的交通信号灯控制系统
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。
  • ¥15 MATLAB卫星二体模型仿真