简体   繁体   中英

websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header

I am trying to set up a websocket connection with the server written in Go and a JavaScript frontend. I have the following files in one directory:

main.go index.html

**This is my Go code in main.go : **

package main


import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func homePage(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./index.html")
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Error in handler:", err)
        return
    }
    log.Println("Client connected.")

    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            log.Println("Fehler in ReadMessage: ", err)
            return
        }

        log.Println(string(p))

        //echo message to client
        if err := conn.WriteMessage(messageType, p); err != nil {
            log.Println(err)
            return
        }
    }
}

func setupRoutes() {
    http.HandleFunc("/ws", homePage)
}

func main() {
    fmt.Println("Server gestartet")
    setupRoutes()
    log.Fatal(http.ListenAndServe(":9100", nil))

}

And this is the HTML and JavaScript in index.html:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Some unimportant html </title>
</head>
<body>
    
    <script>


        let socket = new WebSocket("ws://localhost:9100/ws");
        console.log("Websocket started.");

        socket.onOpen = () => {
            console.log("Client started.");
        }

        socket.onclose = (event) => {
            console.log("Socket closed: ", event);
        }

        socket.onError = (error) => {
            console.log("Socket Error: ", error);
        }

        socket.onMessage = (msg) => {
            console.log(msg);
        }
    </script>
</body>
</html>

However, when I run the thing with go run main.go I get the following error:

2022/11/20 16:38:33 http: superfluous response.WriteHeader call from github.com/gorilla/websocket.(*Upgrader).returnError (server.go:83)
2022/11/20 16:38:33 Error in handler: websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header
2022/11/20 16:38:33 Error in handler: write tcp [::1]:9100->[::1]:63712: wsasend: Eine bestehende Verbindung wurde softwaregesteuert durch den Hostcomputer abgebrochen.
2022/11/20 16:39:06 Error in handler: write tcp [::1]:9100->[::1]:63733: wsasend: Eine bestehende Verbindung wurde softwaregesteuert durch den Hostcomputer abgebrochen.
exit status 0xc000013a

The German lines mean "the existing connection was software controlled terminated by the host computer"

I am missing something and my understanding doesn't run deep enough to pinpoint what's wrong. Any help is much appreciated!

I thought maybe my JS Websocket is missing an upgrade, but in Chrome I can see the following request header for Request URL ws://localhost:9100/ws that says "Upgrade:websocket"

Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: Upgrade
Host: localhost:9100
Origin: http://localhost:9100
Pragma: no-cache
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Key: h3DWLuXsI9/GkTo+sIjyzw==
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

Thanks to the helpful comment by Cerise Limón I was able to fix it. The problem was that I needed one endpoint for the index file and another one for the websocket. So I changed the relevant parts to this:

func websocketHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil) //conn is a websocket connection (aus http wird websocket protokoll)
    if err != nil {
        log.Println("Error in handler:", err)
        return
    }
    log.Println("Client connected.")

    
    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            log.Println("Fehler in ReadMessage: ", err)
            return
        }

        log.Println(string(p))

        //echo message to client
        if err := conn.WriteMessage(messageType, p); err != nil {
            log.Println(err)
            return
        }
    }
}

func homePage(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./index.html")
}

func setupRoutes() {
    http.HandleFunc("/", homePage)
    http.HandleFunc("/ws", websocketHandler)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM