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

I need a golang client that can upgrade from an http get response to a websocket connection.

I have a JS client that works and I've seen direct ws client connections but I have to upgrade from http. I have tried looking for other 3GL solutions (Java, C#, Python) but I need to be able to implement the upgrade in Go. I have seen Dart detaching the socket and creating a websocket from it.

WebSocket.fromUpgradedSocket

I noticed Client does not support Hijack but the discussion didn't get me anywhere. I am using github.com/gorilla/websocket but can change that if it helps.

Server:


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
", req)
        if req.Method == "ping" {
            fmt.Printf("Param=%v
", 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))
}

Client:


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))
}

I get an error

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

Which doesn't surprise me because I haven't upgraded the connection. So how do I go an upgrade in Go?

1个回答



使用 Gorilla客户端拨打网络套接字连接:</ p>

  func main(){
c,_,err:= websocket.DefaultDialer.Dial( “ ws:// localhost:5002 / ws”,nil)
如果err!= nil {
//处理错误
}
延迟c.Close()

//用c做某事, * websocket.Conn

}
</ code> </ pre>

“拨号”方法向服务器发出GET请求,请求升级到WebSocket协议。 成功完成升级后,Dial将返回 * websocket.Conn </ code>。</ p>
</ div>

展开原文

原文

Use the Gorilla client to dial websocket connections:

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

}

The Dial method issues a GET to the server requesting an upgrade to the WebSocket protocol. On successful completion of the upgrade, Dial returns a *websocket.Conn.

douchuang4181
douchuang4181 谢谢。 Gorilla提供的HTTP升级就足够了。 我让我不得不自己处理HTTP升级的事情变得过于复杂。
一年多之前 回复
dp815292
dp815292 大猩猩客户端向服务器发出GET请求,请求升级WebSocket协议。 如果必须使用从net / http包返回的http.Response,请编辑问题以解释原因。 在Go中拨入服务器的常用方法是使用现有的客户端库之一(Gorilla,x / net / websocket)。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问