create intial db, models, websocket and architecture.
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package websocket
|
||||
|
||||
type Hub struct {
|
||||
rooms map[string]*Room
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
rooms: make(map[string]*Room),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) GetOrCreateRoom(roomID string) *Room {
|
||||
if _, ok := h.rooms[roomID]; !ok {
|
||||
h.rooms[roomID] = NewRoom(roomID)
|
||||
}
|
||||
return h.rooms[roomID]
|
||||
}
|
||||
|
||||
func (h *Hub) CleanupRoom(roomID string) {
|
||||
room := h.rooms[roomID]
|
||||
if len(room.clients) == 0 {
|
||||
delete(h.rooms, roomID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package websocket
|
||||
|
||||
import "github.com/gorilla/websocket"
|
||||
|
||||
type Client struct {
|
||||
conn *websocket.Conn
|
||||
room *Room
|
||||
}
|
||||
|
||||
type Room struct {
|
||||
id string
|
||||
clients map[*Client]bool
|
||||
}
|
||||
|
||||
func NewRoom(id string) *Room {
|
||||
return &Room{
|
||||
id: id,
|
||||
clients: make(map[*Client]bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Room) Register(client *Client) {
|
||||
r.clients[client] = true
|
||||
}
|
||||
|
||||
func (r *Room) Unregister(client *Client) {
|
||||
delete(r.clients, client)
|
||||
client.conn.Close()
|
||||
}
|
||||
|
||||
func (r *Room) Broadcast(message []byte) {
|
||||
for client := range r.clients {
|
||||
err := client.conn.WriteMessage(websocket.TextMessage, message)
|
||||
if err != nil {
|
||||
r.Unregister(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user