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)
}
douxu3315
douxu3315 我尝试了github.com/gorilla/websocket/blob/master/examples/echo/…中的示例。但是他们会监听直到收到中断信号,然后关闭连接。如何不使用通道和for-select语句重写该示例?
接近 3 年之前 回复
dongshaidu2456
dongshaidu2456 拨打连接,编写消息,阅读消息,然后关闭连接。无需使用渠道。显示到目前为止您尝试过的内容。
接近 3 年之前 回复
drsl90685154
drsl90685154 您可以更改其他服务器吗?Websocket似乎不太适合这种情况。
接近 3 年之前 回复

1个回答



致电拨号 WriteMessage ,< a href =“ https://godoc.org/github.com/gorilla/websocket#Conn.ReadMessage” rel =“ nofollow noreferrer”> ReadMessage 和依次关闭。</ p>

  c,_,err:= websocket。  DefaultDialer.Dial(url,nil)
if err!= nil {
//处理错误
}
err:= c.WriteMessage(websocket.TextMessage,signedXML)
if err!= nil {
//处理 error
}
_,p,err:= c.ReadMessage()
if err!= nil {
//处理错误
}
c.Close()

// p是[] 收到的第一条消息的字节。
</ code> </ pre>
</ div>

展开原文

原文

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.

dqq22391
dqq22391 更新中的代码对我有用。 curl -d message = hello http:// localhost:8080 / post打印你好。
接近 3 年之前 回复
dscrn1974
dscrn1974 我测试了上面的代码(UPDATE *),并在conn.ReadMessage()之后冻结
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问