2019-10-12 14:07:40 +07:00
|
|
|
package server
|
|
|
|
|
2019-10-13 11:39:17 +07:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
2019-10-12 14:07:40 +07:00
|
|
|
|
|
|
|
var clients = make(map[*websocket.Conn]bool)
|
2019-10-13 11:39:17 +07:00
|
|
|
var connectedUsers = make(map[string]bool)
|
2019-10-12 14:07:40 +07:00
|
|
|
|
|
|
|
func newSession(who *websocket.Conn) {
|
|
|
|
clients[who] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func disconnectSession(who *websocket.Conn) {
|
|
|
|
delete(clients, who)
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleIncomingMessage(who *websocket.Conn, msg string) {
|
2019-10-13 11:39:17 +07:00
|
|
|
message := strings.SplitN(msg, " ", 2)
|
|
|
|
switch message[0] {
|
|
|
|
case "query":
|
|
|
|
if len(message) < 2 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !connectedUsers[message[1]] {
|
|
|
|
who.WriteMessage(websocket.TextMessage, []byte("leave "+message[1]))
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
fmt.Println("Unknown message:" + msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func broadcast(message string) {
|
|
|
|
for k, _ := range clients {
|
|
|
|
k.WriteMessage(websocket.TextMessage, []byte(message))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ConnectUser(mcUsername string) {
|
|
|
|
connectedUsers[mcUsername] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func DisconnectUser(mcUsername string) {
|
|
|
|
delete(connectedUsers, mcUsername)
|
|
|
|
}
|
|
|
|
|
|
|
|
func RequestSync() {
|
|
|
|
broadcast("sync")
|
2019-10-12 14:07:40 +07:00
|
|
|
}
|