将websocket消息发送给两个客户端

时间:2017-09-05 17:48:12

标签: go websocket gorilla

我从大猩猩聊天示例开始了一个个人项目。每当客户呼叫“注册”时,我会检查它是否有对手。假设客户是游戏玩家。我想做的是每两个人将两个客户联系起来。

客户是:

type Client struct {
    hub      *Hub
    opponent *Client
    conn     *websocket.Conn
    send     chan []byte
}

所以当我的客户端呼叫注册时,如果存在一个对手为nil的客户端,我将两个客户端与

绑定
c.opponent = client
client.opponent = c

然后,我发来一条消息:

c.conn.WriteMessage(websocket.TextMessage, dat)
client.conn.WriteMessage(websocket.TextMessage, dat)

但没有人收到消息。如何向两个客户发送消息?

package main

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

func newHub() *Hub {
    return &Hub{
        broadcast:  make(chan []byte),
        register:   make(chan *Client),
        unregister: make(chan *Client),
        clients:    make(map[*Client]bool),
    }
}

func (h *Hub) run() {
    for {
        select {

        // register new client
        case client := <-h.register:
            log.Println("register")
            h.clients[client] = true
            for c := range h.clients {
                if c != client {
                    if c.opponent == nil {
                        c.opponent = client
                        client.opponent = c
                        dat := []byte(`{"foo":"bar"}`)
                        c.conn.WriteMessage(websocket.TextMessage, dat)
                        client.conn.WriteMessage(websocket.TextMessage, dat)
                    }
                }
            }

        case client := <-h.unregister:
            log.Println("unregister")
            if _, ok := h.clients[client]; ok {
                delete(h.clients, client)
                close(client.send)
            }

        case message := <-h.broadcast:
            for client := range h.clients {
                select {
                case client.send <- message:
                default:
                    close(client.send)
                    delete(h.clients, client)
                }
            }

        }
    }
}

0 个答案:

没有答案