Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send the messages actively from golang's websocket server to client

Tags:

I'm a newcomer for the golang and websocket.

I'm trying to write a websocket server which can send the messages actively to client once the handshake is done.

but my server will just only send the message to the client when got the request from the client.

Does anyone know how to implement this feature or where can I find the related answer for that?

Thank you so much.

the source code is as follows:

package main

import (
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte("Hi, the handshake is completed.\n"))
    w.Write([]byte("Let's start to talk something.\n"))
}

func main() {
    http.HandleFunc("/", handler)
    log.Printf("Start to listen on 443.")
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    log.Fatal(err)
}
like image 265
Bjergsen Zhu Avatar asked May 24 '18 05:05

Bjergsen Zhu


People also ask

Can a WebSocket server send message to client?

Messages sent by the server to the client can include plain text messages, binary data, or images. Whenever data is sent, the onmessage function is fired. This event acts as a client's ear to the server. Whenever the server sends data, the onmessage event gets fired.

How do you send a message to a specific user in WebSocket?

These steps need to be performed: Generate a Spring Security Principal name by UUID for each newly connected client by using DefaultHandshakeHandler. Store the UUID if a new message is received. Use @SendToUser instead of @SendTo annotation in the WebSocket controller.

How do I send a WebSocket message to a server?

The client-side WebSocket object has a . send() method that is used to send a message from the client to the server over the WebSocket connection between them. This . send() method accepts a single argument: the data to be sent to the server.

How does the WebSocket receive data on the browser that is sent from server?

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. Following is the API which creates a new WebSocket object.


1 Answers

Thanks you all for you both's help to answer me. and sorry for the very late reply here.

You both's answer is really helpful and I learn a lot.

Finally, I also find the simple way to achieve the same result without using the gorilla, here comes my code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "golang.org/x/net/websocket"
)

func Echo(ws *websocket.Conn) {
    var err error
    msg := `Hi, the handshake it complete!`

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

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

    if err := http.ListenAndServeTLS("10.10.10.10:1010", "server.crt", "server.key", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}
like image 61
Bjergsen Zhu Avatar answered Oct 11 '22 17:10

Bjergsen Zhu