Home > front end >  Websocket closed very quickly
Websocket closed very quickly

Time:06-13

I'm trying this websocket example:

package main

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

    "golang.org/x/net/websocket"
)

func Echo(ws *websocket.Conn) {
    var err error

    for {
        var reply string

        if err = websocket.Message.Receive(ws, &reply); err != nil {
            fmt.Println("Can't receive")
            break
        }

        fmt.Println("Received back from client: "   reply)

        msg := "Received:  "   reply
        fmt.Println("Sending to client: "   msg)

        if err = websocket.Message.Send(ws, msg); err != nil {
            fmt.Println("Can't send")
            break
        }
    }
}

func main() {
    http.Handle("/", websocket.Handler(Echo))

    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

With this client:

<html>
<head></head>
<body>
    <script type="text/javascript">
        var sock = null;
        var wsuri = "ws://localhost:1234";

        window.onload = function() {

            console.log("onload");

            sock = new WebSocket(wsuri);

            sock.onopen = function() {
                console.log("connected to "   wsuri);
            }

            sock.onclose = function(e) {
                console.log("connection closed ("   e.code   ")");
            }

            sock.onmessage = function(e) {
                console.log("message received: "   e.data);
            }
        };

        function send() {
            var msg = document.getElementById('message').value;
            sock.send(msg);
        };
    </script>
    <h1>WebSocket Echo Test</h1>
    <form>
        <p>
            Message: <input id="message" type="text" value="Hello, world!">
        </p>
    </form>
    <button onclick="send();">Send Message</button>
</body>
</html>

But getting the below error: enter image description here

CodePudding user response:

I had trouble with std lib webscokets and (like most Go people) use Gorilla websocket package. Try this code (based on my working code):

package main

import (
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

func echo(w http.ResponseWriter, r *http.Request) {
    conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
    if err != nil {
        http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
        return
    }
    for {
        messType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println("read:", err)
            break
        }
        log.Printf("recv: %s", message)
        err = conn.WriteMessage(messType, message)
        if err != nil {
            log.Println("write:", err)
            break
        }
    }
}

func main() {
    http.HandleFunc("/", echo)

    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

I think you'll have a lot more joy this way.

  •  Tags:  
  • go
  • Related