-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_room.go
61 lines (50 loc) · 1.38 KB
/
example_room.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
package main
import (
"flag"
"fmt"
"github.com/trevex/golem"
"log"
"net/http"
)
var addr = flag.String("addr", ":8080", "http service address")
// Create single room.
var myroom = golem.NewRoom()
// Join myroom.
func join(conn *golem.Connection) {
myroom.Join(conn)
fmt.Println("Someone joined myroom.")
}
// Simple string will be received as message.
type RoomMessage struct {
Msg string `json:"msg"`
}
// Emits the received message to all members of room.
func msg(conn *golem.Connection, data *RoomMessage) {
myroom.Emit("msg", &data)
fmt.Println("\"" + data.Msg + "\" sent to members of myroom.")
}
func connClose(conn *golem.Connection) {
// Make sure to get rid of player, not necessary!
// If room is used often, leaving on disconnects
// can be left out, because when sending to lobbies
// unavailable connection are automatically sorted out.
myroom.Leave(conn)
fmt.Println("Someone left myroom.")
}
func main() {
flag.Parse()
// Create a router
myrouter := golem.NewRouter()
// Add the events to the router
myrouter.On("join", join)
myrouter.On("msg", msg)
myrouter.OnClose(connClose)
// Serve the public files
http.Handle("/", http.FileServer(http.Dir("./public")))
// Handle websockets using golems handler
http.HandleFunc("/ws", myrouter.Handler())
// Listen
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}