Golang websocket客户端,获得结果后关闭连接

时间:2017-10-05 10:15:26

标签: go websocket gorilla

我如何实现这种情况:

1.我有LoginHandler接收一些用户数据 - email和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.我需要通过websocket

将signedXml发送到另一台服务器

3.保存结果(成功或错误)

4.关闭连接

每个HTTP请求都会打开连接,发送1条消息,得到1条结果,最后关闭套接字。我在尝试使用频道,但没有成功。这有可能实现我的案例吗?

更新

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\n", message)
    log.Printf("connecting to %s\n", 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 个答案:

答案 0 :(得分:1)

依次致电DialWriteMessageReadMessageClose

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.