send websocket message to two clients

306 Views Asked by At

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

        }
    }
}
0

There are 0 best solutions below