向两个客户端发送websocket消息

I started a personal project from gorilla chat example. Every time a client calls "register" I check if it has an opponent. Suppose clients are game players. What I am trying to do is to couple clients two per two.

Clients are:

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

So when I client call register, if exists one client with opponent nil, I tie two clients with

c.opponent = client
client.opponent = c

And then, I send together a message:

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

but no one receive the message. How can I send a message to just two clients?

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

        }
    }
}
doucai7294
doucai7294 是的,这将解决数据争用问题。尽管应该解决数据争用问题,但这可能不是这里的问题。添加一些日志语句以确认正在配对。
接近 3 年之前 回复
dtjxhf595733
dtjxhf595733 c。发送<-dat和client.send<-dat吗?
接近 3 年之前 回复
dongtie0929
dongtie0929 将消息发送到通道client.send,而不是直接写入连接,以避免webscoket写入过程中的数据争用。使用调试器或通过添加一些日志记录代码来确认配对代码正在执行。
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问