-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.go
98 lines (90 loc) · 2.7 KB
/
websockets.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
package main
import (
"net/http"
"fmt"
"strings"
"github.com/gorilla/websocket"
)
// Global Variables are in all caps.
var CLIENTS = make(map[*websocket.Conn]bool)
var BROADCAST = make(chan Message)
var UPGRADER = websocket.Upgrader{}
var STATE = "PAUSED"
var TIME = float32(0)
var VIDEO = "http://www.youtube.com/v/dQw4w9WgXcQ?version=3Message"
var QUEUE []string
// Define our message object
type Message struct {
Event string `json:"Event"`
Value float32 `json:"Value"`
URL string `json:"URL"`
Date int `json:"Date"`
}
func WebsocketHandler(w http.ResponseWriter, r *http.Request) {
// convert to WS, store in client global.
ws, err := UPGRADER.Upgrade(w, r, w.Header())
if err != nil {
fmt.Println(err)
}
// Gonna check if they are in the list, if not, say hello and register them.
if (!CLIENTS[ws]){
defer ws.Close()
CLIENTS[ws] = true
fmt.Println("Adding new connection!");
// Need to know if he is not first, so we can sync everyone.
if(len(CLIENTS) > 0){
fmt.Println("Syncing!");
broadcast(Message{"SYNC",float32(TIME),VIDEO,0}, ws)
}
ws.WriteJSON(Message{"HELLO", float32(TIME), VIDEO, 0})
}
for {
var msg Message
err := ws.ReadJSON(&msg)
if err != nil {
fmt.Println("Error reading json.", err)
}
//fmt.Println("Message received! :: " + msg.Event)
if(strings.Compare(msg.Event, "PLAYING") == 0 || strings.Compare(msg.Event, "PAUSED") == 0){
STATE = msg.Event
broadcast(msg, ws)
}else if(strings.Compare(msg.Event, "VIDEO") == 0){
fmt.Println("Video Changing to :: " + msg.URL)
VIDEO = msg.URL
TIME = 0
broadcast(msg, ws)
}else if(strings.Compare(msg.Event, "UPDATE") == 0){
//fmt.Println("Time Changing to :: " + string(msg.Value))
TIME = msg.Value
broadcast(msg, ws)
}else if(strings.Compare(msg.Event, "QUEUE") == 0){
//ws.WriteJSON(Message{"UPDATE",float32(TIME),VIDEO,0})
QUEUE = append(QUEUE, msg.URL)
//fmt.Println(QUEUE)
}else if(strings.Compare(msg.Event, "STOPPED") == 0){
//ws.WriteJSON(Message{"UPDATE",float32(TIME),VIDEO,0})
fmt.Println("STOP RECIEVED")
if (len(QUEUE) > 0){
fmt.Println(QUEUE)
VIDEO=QUEUE[0]
TIME=0
broadcast(Message{"VIDEO", 0, QUEUE[0], 0}, nil)
QUEUE = QUEUE[1:]
}else{
fmt.Println("Queue Empty..")
}
}
}
}
func broadcast(msg Message, sender *websocket.Conn){
for client := range CLIENTS {
if(client != sender){
err := client.WriteJSON(msg)
if(err != nil){
fmt.Printf("error: %v", err)
client.Close()
delete(CLIENTS, client)
}
}
}
}