/
websocket.go
98 lines (82 loc) · 2.13 KB
/
websocket.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
/*
* EliasDB
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package ecal
import (
"encoding/json"
"sync"
"time"
"github.com/gorilla/websocket"
)
/*
WebsocketConnection models a single websocket connection.
Websocket connections support one concurrent reader and one concurrent writer.
See: https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency
*/
type WebsocketConnection struct {
CommID string
Conn *websocket.Conn
RMutex *sync.Mutex
WMutex *sync.Mutex
}
/*
NewWebsocketConnection creates a new WebsocketConnection object.
*/
func NewWebsocketConnection(commID string, c *websocket.Conn) *WebsocketConnection {
return &WebsocketConnection{
CommID: commID,
Conn: c,
RMutex: &sync.Mutex{},
WMutex: &sync.Mutex{}}
}
/*
Init initializes the websocket connection.
*/
func (wc *WebsocketConnection) Init() {
wc.WMutex.Lock()
defer wc.WMutex.Unlock()
wc.Conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"init_success","payload":{}}`))
}
/*
ReadData reads data from the websocket connection.
*/
func (wc *WebsocketConnection) ReadData() (map[string]interface{}, bool, error) {
var data map[string]interface{}
var fatal = true
wc.RMutex.Lock()
_, msg, err := wc.Conn.ReadMessage()
wc.RMutex.Unlock()
if err == nil {
fatal = false
err = json.Unmarshal(msg, &data)
}
return data, fatal, err
}
/*
WriteData writes data to the websocket.
*/
func (wc *WebsocketConnection) WriteData(data map[string]interface{}) {
wc.WMutex.Lock()
defer wc.WMutex.Unlock()
jsonData, _ := json.Marshal(map[string]interface{}{
"commID": wc.CommID,
"type": "data",
"payload": data,
})
wc.Conn.WriteMessage(websocket.TextMessage, jsonData)
}
/*
Close closes the websocket connection.
*/
func (wc *WebsocketConnection) Close(msg string) {
wc.Conn.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(
websocket.CloseNormalClosure, msg), time.Now().Add(10*time.Second))
wc.Conn.Close()
}