Websocket在Echo Framework中向所有客户端发送消息

我相信这个问题与此。 </ p>

但是我在Echo框架中使用了websocket而不是Gorilla。 因此,我认为方法会有所不同。</ p>

Echo确实提供了 。但是它仅显示了如何与单个客户端连接。 当一个以上的客户端时,其他客户端不会收到来自服务器的消息。 </ p>

我如何使服务器向所有连接的客户端广播消息?</ p>

所引用链接的可接受答案是,我必须使用连接池 向所有连接广播消息。 如何在Echo框架中做到这一点?</ p>
</ div>

展开原文

原文

I believe that this question is almost the same with this.

But I use websocket in Echo framework instead of Gorilla. So I think the approach will be different.

Echo does provide the example. But it only shows how to connect with single client. When there are more than one client, the other clients don't receive message from server.

How do I make the server broadcasts message to all connected clients?

The accepted answer from referred link says that I have to use connection pool to broadcast messages to all connections. How can I do this in Echo framework?

1个回答

You indeed need to follow the same principle of connection pool.

Here is the Echo example, with a very basic implementation of a pool:

package main

import (
    "fmt"

    "sync"

    "github.com/labstack/echo"
    mw "github.com/labstack/echo/middleware"
    "golang.org/x/net/websocket"
)

var connectionPool = struct {
    sync.RWMutex
    connections map[*websocket.Conn]struct{}
}{
    connections: make(map[*websocket.Conn]struct{}),
}

func main() {
    e := echo.New()

    e.Use(mw.Logger())
    e.Use(mw.Recover())

    e.Static("/", "public")
    e.WebSocket("/ws", func(c *echo.Context) (err error) {
        ws := c.Socket()

        connectionPool.Lock()
        connectionPool.connections[ws] = struct{}{}

        defer func(connection *websocket.Conn){
            connectionPool.Lock()
            delete(connectionPool.connections, connection)
            connectionPool.Unlock()
        }(ws)

        connectionPool.Unlock()

        msg := ""

        for {
            if err = websocket.Message.Receive(ws, &msg); err != nil {
                return err
            }
            err = sendMessageToAllPool(msg)
            if err != nil {
                return err
            }
            fmt.Println(msg)
        }
        return err
    })

    e.Run(":1323")
}

func sendMessageToAllPool(message string) error {
    connectionPool.RLock()
    defer connectionPool.RUnlock()
    for connection := range connectionPool.connections {
        if err := websocket.Message.Send(connection, message); err != nil {
            return err
        }
    }
    return nil
}
dongyishe6689
dongyishe6689 非常感谢,赫克托。 我得到了像魅力一样的工作。
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐