-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketServer.go
56 lines (46 loc) · 1.08 KB
/
socketServer.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
package gws
import (
"log"
"net/http"
"strconv"
)
type SocketServer struct {
port int
route string
hub *Hub
}
func NewSocketServer(port int, route string) *SocketServer {
return &SocketServer{
port: port,
route: route,
hub: nil,
}
}
func messageHandler(msg interface{}, hub *Hub, fn func(interface{})) {
if hub == nil {
log.Fatalln("Tried sending a message before starting the socket server")
return
}
fn(msg)
}
func (s *SocketServer) SendMessage(msg Message) {
messageHandler(msg, s.hub, func(m interface{}) {
s.hub.toClient <- m.(Message)
})
}
func (s *SocketServer) BroadcastMessage(msg []byte) {
messageHandler(msg, s.hub, func(m interface{}) {
s.hub.broadcast <- m.([]byte)
})
}
func (s *SocketServer) Start(outbound chan Message) {
s.hub = newHub()
go s.hub.run(outbound)
http.HandleFunc(s.route, func(w http.ResponseWriter, r *http.Request) {
serveWs(s.hub, w, r)
})
err := http.ListenAndServe("0.0.0.0:"+strconv.Itoa(s.port), nil)
if err != nil {
log.Fatal("ListenAndServer: ", err)
}
}