发送连接升级后,如何将客户端http连接升级到golang中的websockets

时间:2019-04-05 13:24:10

标签: http go websocket client upgrade

我需要一个可以从http get响应升级到websocket连接的golang客户端。

我有一个可运行的JS客户端,并且我已经看到直接与ws客户端的连接,但是必须从http升级。我曾尝试寻找其他3GL解决方案(Java,C#,Python),但我需要能够在Go中实现升级。我见过Dart拆下插座并从中创建一个websocket。

WebSocket.fromUpgradedSocket

我注意到了Client does not support Hijack,但是讨论并没有带我过去。 我正在使用github.com/gorilla/websocket,但如果有帮助,可以更改它。

服务器:


func main() {
    srv := Srv{}
    count = 0
    http.HandleFunc("/", srv.handleRoot)
    http.HandleFunc("/ws", srv.handleWs)
    log.Fatal(http.ListenAndServe(":5002", nil))
}

func (tool *Srv) handleRoot(w http.ResponseWriter, r *http.Request) {

    webSocketKey := hdr.Get("Sec-WebSocket-Key")
    log.Printf("Socket key = '%v'", webSocketKey)

    secWsAccept := computeAcceptKey(webSocketKey)
    log.Printf("Accept = '%v'", secWsAccept)
    w.Header().Add("sec-websocket-accept", secWsAccept)
    w.Header().Add("upgrade", "websockt")
    w.Header().Add("connection", "upgrade")
    w.WriteHeader(101)
}

func (tool *Srv) handleWs(w http.ResponseWriter, r *http.Request) {
    var upgrader = websocket.Upgrader{}
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatalf("Websocket fatal error. %v", err)
    }
    tool.conn = conn
    go tool.serviceWsRequests()
}

func (tool *Srv) serviceWsRequests() {
    for {
        log.Printf("starting ws")
        req := request{}
        err := tool.conn.ReadJSON(&req)
        if err != nil {
            log.Printf("Failed to decode ws message. %v", err)
            break
        }
        fmt.Printf("Got request. %v\n", req)
        if req.Method == "ping" {
            fmt.Printf("Param=%v\n", req.Parameters)
        }
    }
}

var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")

func computeAcceptKey(challengeKey string) string {
    h := sha1.New()
    h.Write([]byte(challengeKey))
    h.Write(keyGUID)
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

客户:


func main() {
    tr := &http.Transport{
        MaxIdleConns:       10,
        IdleConnTimeout:    30 * time.Second,
        DisableCompression: true,
    }
    client := &http.Client{
        Transport: tr,
        // Do NOT follow redirects
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    wsKey, err := generateKey()
    if err != nil {
        log.Printf("Cannot generate challenge key %v", err)
    }

    // Get request for ws upgrade.
    req, err := http.NewRequest("GET", "http://localhost:5002", nil)
    req.Header.Add("Connection", "Upgrade")
    req.Header.Add("Upgrade", "websocket")
    req.Header.Add("Sec-WebSocket-Version", "13")
    req.Header.Add("Sec-WebSocket-Key", wsKey)
    log.Printf("ws key '%v'", wsKey)
    resp, err := client.Do(req)

    if err != nil {
        log.Printf("Get error %v", err)
    }
    defer func() {
        if resp != nil {
            err = resp.Body.Close()
        }
    }()

    log.Printf("Status='%v', proto='%v'", resp.Status, resp.Proto)
    body, err := ioutil.ReadAll(resp.Body)
    hdr := resp.Header
    for k, v := range hdr{
        log.Printf("%v : %v", k, v)
    }
    log.Printf("Body = %v", string(body))

    resp, err = http.Get("ws://localhost:5002/ws")
    if err != nil {
        log.Printf("Error '%v'", err)
    }

}

func generateKey() (string, error) {
    p := make([]byte, 16)
    if _, err := io.ReadFull(rand.Reader, p); err != nil {
        return "", err
    }
    return base64.StdEncoding.EncodeToString(p), nil
}

var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")

func computeAcceptKey(challengeKey string) string {
    h := sha1.New()
    h.Write([]byte(challengeKey))
    h.Write(keyGUID)
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

我收到错误

Error 'Get ws://localhost:5002/ws: unsupported protocol scheme "ws"'

这并不奇怪,因为我还没有升级连接。 那么如何在Go中进行升级?

1 个答案:

答案 0 :(得分:3)

使用Gorilla client拨打网络套接字连接:

func main() {
    c, _ , err := websocket.DefaultDialer.Dial("ws://localhost:5002/ws", nil)
    if err != nil {
        // handle error
    }
    defer c.Close()

    // do something with c, a *websocket.Conn

}

Dial方法向服务器发出GET请求,要求升级WebSocket协议。成功完成升级后,Dial将返回*websocket.Conn