-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
118 lines (100 loc) · 2.61 KB
/
client.go
File metadata and controls
118 lines (100 loc) · 2.61 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"log"
"math/rand"
"fmt"
"net/http"
"github.com/gorilla/websocket"
"github.com/google/uuid"
"google.golang.org/protobuf/proto"
events "github.com/walshyb/whiteboard/proto"
)
type Client struct {
conn *websocket.Conn
hub *Hub
send chan *events.ServerMessage
handshake chan *events.ServerMessage
name string
id string
}
var adjectives = [8]string{"bright", "silent", "rough", "narrow", "gentle", "sharp", "steady", "fragile",}
var nouns = [8]string{"river","lantern","stone", "meadow","circuit","anchor","window","compass",}
func makeNewClient(hub *Hub, w http.ResponseWriter, r *http.Request) *Client{
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Error upgrading:", err)
return nil
}
random_adjective := adjectives[rand.Intn(len(adjectives))]
random_noun := nouns[rand.Intn(len(nouns))]
return &Client {
conn: conn,
hub: hub,
send: make(chan *events.ServerMessage),
handshake: make(chan *events.ServerMessage),
name: fmt.Sprintf("%s %s", random_adjective, random_noun),
id: uuid.New().String(),
}
}
/*
Read stream of messages from clients and publish to redis channel
*/
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
//log.Printf("error: %v", err)
return
}
// unmarshal inbound message
var msg events.ClientMessage
if err := proto.Unmarshal(message, &msg); err != nil {
log.Printf("invalid message: %v", err)
continue
}
// assign server ID
msg.ServerId = &c.hub.serverId
// re marshall
protoBytes, err := proto.Marshal(&msg)
if err != nil {
log.Printf("marshal error: %v", err)
continue
}
// publish to Redis
c.hub.redis.Publish(c.hub.ctx, "mouse_events", protoBytes)
}
}
func (c *Client) writePump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
if !ok {
// The hub closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
continue
}
protoBytes , _ := proto.Marshal(message)
err := c.conn.WriteMessage(websocket.BinaryMessage, protoBytes)
if err != nil {
log.Println("WriteMessage error:", err)
continue
}
case handshake := <-c.handshake:
if (handshake == nil) {
continue
}
w,_ := c.conn.NextWriter(websocket.BinaryMessage)
protoBytes, _ := proto.Marshal(handshake)
w.Write(protoBytes)
w.Close()
}
}
}