-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatServer.go
82 lines (66 loc) · 1.54 KB
/
chatServer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
)
type WsServer struct {
clients map[*Client]bool
register chan *Client
unregister chan *Client
broadcast chan []byte
rooms map[*Room]bool
}
// NewWebsocketServer creates a new WsServer type
func NewWebsocketServer() *WsServer {
return &WsServer{
clients: make(map[*Client]bool),
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan []byte),
rooms: make(map[*Room]bool),
}
}
// Run our websocket server, accepting various requests
func (server *WsServer) Run() {
for {
select {
case client := <-server.register:
server.registerClient(client)
case client := <-server.unregister:
server.unregisterClient(client)
case message := <-server.broadcast:
server.broadcastToClients(message)
}
}
}
func (server *WsServer) registerClient(client *Client) {
fmt.Println("user masuk")
server.clients[client] = true
}
func (server *WsServer) unregisterClient(client *Client) {
fmt.Println("user keluar")
delete(server.clients, client)
}
func (server *WsServer) broadcastToClients(message []byte) {
for client := range server.clients {
client.send <- message
}
}
func (server *WsServer) findRoomByName(name string) *Room {
var foundRoom *Room
for room := range server.rooms {
if room.Name == name {
foundRoom = room
break
}
}
return foundRoom
}
func (server *WsServer) createRoom(name string) *Room {
room := NewRoom(name)
go room.RunRoom()
server.rooms[room] = true
return room
}
func (room *Room) GetName() string {
return room.Name
}