如何从golang的websocket服务器向客户端主动发送消息

我是golang和websocket的新手。</ p>

我' m尝试编写一个websocket服务器,一旦握手完成,该服务器便可以将消息主动发送给客户端。</ p>

,但是我的服务器只会在收到来自服务器的请求后才将消息发送给客户端 客户端。</ p>

有人知道如何实现此功能,或者在哪里可以找到相关的答案? </ p>

非常感谢。</ p>

源代码如下:</ p>

 程序包主要 

import(
“ log”
“ net / http”

func处理程序(带有http.ResponseWriter,req * http.Request){
w.Header()。Set(“ Content -Type“,” text / plain“)
w.Write([] byte(”嗨,握手完成了。
“))
w.Write([] byte(”让我们开始谈谈。

“))
}

func main(){
http.HandleFunc(” /“,handler)
log.Printf(”开始侦听443。“)
err:= http。 ListenAndServeTLS(“:443”,“ server.crt”,“ server.key”,nil)
log.Fatal(err)
}
</ code> </ pre>
</ div>

展开原文

原文

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.
"))
    w.Write([]byte("Let's start to talk something.
"))
}

func main() {
    http.HandleFunc("/", handler)
    log.Printf("Start to listen on 443.")
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    log.Fatal(err)
}

dongmao3148
dongmao3148 这是纯HTTP处理程序。没有实现websocket协议的代码。考虑使用大猩猩包。
大约 2 年之前 回复

3个回答



尝试使用包 websocket < / a>。</ p>

这是从 Godoc :</ p>

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

func处理程序( w http.ResponseWriter,r * http.Request){
conn,err:= upgrader.Upgrade(w,r,nil)
如果err!= nil {
log.Println(err)
return
}
延迟conn.Close()

msg:= [] byte(“让我们开始谈谈。”)
err = conn.WriteMessage(websocket.TextMessage,msg)
如果err!= nil {
log.Println(err)
}

//做其他事情...
}
</ code> </ pre>
</ div>

展开原文

原文

Try package websocket.

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



首先,您的服务器位于http而非websocket上(为此,您可以使用大猩猩将其升级到websocket)</ p>

秒,在客户端发出请求之前,您无法与他联系(daaa)</ p>
</ div>,因此无法回复他

展开原文

原文

first of all, youre server is on http not websocket (for that you can upgrade it to websocket using gorilla e.g)

second, before client making a request there is no way to response him because you have no connection with him (daaa)



感谢大家对我的帮助。
对于此处的答复很晚表示抱歉。 </ p>

你们两个人的回答都非常有帮助,我学到了很多东西。</ p>

最后,我还找到了无需使用以下方法即可达到相同结果的简单方法 大猩猩,这是我的代码:</ p>

 包main 

import(
“ fmt”
“ log”
“ net / http”
“ golang。 org / x / net / websocket“

func Echo(ws * websocket.Conn){
var err error
msg:=嗨,握手完成了!

for {\ n如果err = websocket.Message.Send(ws,msg); err!= nil {
fmt.Println(“无法发送”)
}其他{
fmt.Println(“ Sending”)
}
}
}

func main(){

http.Handle(“ /”,websocket.Handler(Echo))

如果错误:= http.ListenAndServeTLS(“ 10.10.10.10:1010”,“ server.crt”,“ server.key”,无 ); err!= nil {
log.Fatal(“ ListenAndServe:”,err)
}
}
</ code> </ pre>
</ div>

展开原文

原文

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐