-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
249 lines (209 loc) · 5.99 KB
/
main.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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"log"
"math/rand"
"net/http"
"time"
)
var queue = make(map[string]*Client) // global queue
var (
newline = []byte{'\n'}
space = []byte{' '}
)
type Client struct {
clientID string // userID in supabase
conn *websocket.Conn // websocket connection object
send chan []byte // channel for sending messages
receive chan []byte // channel for reciving messages
pastMatches []string // past matched clientsIDs (could be accepted or rejected)
}
type Message struct {
MsgType string `json: "MsgType"`
Data string `json:"Data"`
}
func main() {
go match()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "404: Page not found", 404)
}) // 404 to all http requests
http.HandleFunc("/ws", serveWs)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func parseResponse(jsonResponse []byte) string {
// var msg string
// _ = json.Unmarshal(jsonResponse, &msg)
log.Println("response was: ", string(jsonResponse))
return string(jsonResponse)
}
func askForApproval(clientA, clientB *Client) {
candidateA, _ := json.Marshal(&Message{
MsgType: "candidate",
Data: clientA.clientID,
})
candidateB, _ := json.Marshal(&Message{
MsgType: "candidate",
Data: clientB.clientID,
})
log.Printf("Trying to match users %v and %v", clientA.clientID, clientB.clientID)
log.Printf("Sending candidates %v and %v", string(candidateA), string(candidateB))
clientB.send <- candidateA
clientA.send <- candidateB
responseA := parseResponse(<-clientA.receive)
responseB := parseResponse(<-clientB.receive)
for responseA != "" && responseB != "" {
if responseA == "accept" && responseB == "accept" {
// create room id
roomID := uuid.New().String()
log.Println(roomID, clientA.clientID, clientB.clientID)
// selected candidates become peers, both have common roomID
roomMsg, _ := json.Marshal(&Message{
MsgType: "room",
Data: roomID,
})
clientB.send <- roomMsg
clientA.send <- roomMsg
break
} else {
log.Println("At least one response was not 'accept'.")
queue[clientA.clientID] = clientA
queue[clientB.clientID] = clientB
}
}
}
func existsIn(target string, arr []string) bool {
for _, element := range arr {
if element == target {
return true
}
}
return false
}
func match() {
for {
if len(queue) > 1 {
var clientA, clientB *Client
var randIndexA, randIndexB int
// select random clients
for {
keys := make([]string, 0, len(queue))
for key := range queue {
keys = append(keys, key)
}
randIndexA = rand.Intn(len(keys))
clientA = queue[keys[randIndexA]]
randIndexB = rand.Intn(len(keys))
clientB = queue[keys[randIndexB]]
if clientB == clientA || existsIn(clientB.clientID, clientA.pastMatches) {
continue
} else {
clientA.pastMatches = append(clientA.pastMatches, clientB.clientID)
clientB.pastMatches = append(clientB.pastMatches, clientA.clientID)
break
}
}
delete(queue, clientA.clientID)
delete(queue, clientB.clientID)
log.Println("Waiting for approval")
go askForApproval(clientA, clientB)
log.Println("j aiccha")
} else {
log.Printf("Not enough users to match. Online: %d user(s)", len(queue))
time.Sleep(10 * time.Second)
}
}
}
func serveWs(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Upgrade(w, r, nil, 512, 512)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return // stops execution if connection upgrade fails
}
userID := r.URL.Query().Get("userid") // wss://localhost:8080?userid=0123435
sendChannel := make(chan []byte, 512) // each message is a slice of bytes, 512 messages can be stored in buffer
receiveChannel := make(chan []byte, 512)
pastMatches := []string{userID} // ading self to past matches to prevent self matching
newClient := &Client{
clientID: userID,
conn: conn,
send: sendChannel,
receive: receiveChannel,
pastMatches: pastMatches,
}
queue[userID] = newClient
go newClient.writePump()
go newClient.readPump()
}
func (c *Client) readPump() {
defer func() {
log.Println("Closed at location 1")
c.conn.Close()
}()
c.conn.SetReadLimit(131072)
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
c.conn.SetPongHandler(func(string) error {
log.Println("Closed at location 2")
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Println("Closed at location 3")
log.Printf("UnexpectedCloseError: %v", err)
}
break
}
// slice upto the first ',' - this is the messageType
//
// messageType := string(message[:idx])
// messageBody:=string(message[idx+1:])
c.receive <- message
}
}
func (c *Client) writePump() {
ticker := time.NewTicker(50 * time.Second)
defer func() {
log.Println("Closed at location 4")
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if !ok {
log.Println("Closed at location 5")
// The server closed the channel
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Println("Closed at location 6")
log.Println(message)
return
}
w.Write(message)
// Add queued chat messages to the current websocket message
n := len(c.send)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
log.Println("Closed at location 7")
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Println("Closed at location 8")
return
}
}
}
}