问题描述

我是golang和websocket的新手.

I'm a newcomer for the golang and websocket.

我正在尝试编写一个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?

非常感谢您.

源代码如下:

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

推荐答案

尝试使用包 websocket .

这是从 Godoc 中获得的简单示例:

Here's a simple example grab from the Godoc:

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

func handler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()

    msg := []byte("Let's start to talk something.")
    err = conn.WriteMessage(websocket.TextMessage, msg)
    if err != nil {
        log.Println(err)
    }

    // do other stuff...
}

这篇关于如何主动将消息从golang的websocket服务器发送到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!