-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
78 lines (66 loc) · 1.45 KB
/
connection.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
package main
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"golang.org/x/net/websocket"
"time"
)
type Payload struct {
Message string `json:"message"`
Host string `json:"host"`
Time string `json:"time"`
}
const (
// READER type connection
READER = iota
// PROXY type connection
PROXY
)
// WebSocket connection wrapper struct
// Manage connection-id, and close/message event handler.
type Connection struct {
// Connection type
Type int
// Connection ID
// this fields supplied after instantiate
Id string
// WebSocket connection
conn *websocket.Conn
// Event handler of close connection
OnClose func()
// Event handler of message incoming
OnMessage func(Payload)
}
// Create New connection
func NewConnection(connType int, conn *websocket.Conn) *Connection {
hash := sha1.Sum([]byte(fmt.Sprint(time.Now().UnixNano())))
return &Connection{
Type: connType,
Id: hex.EncodeToString(hash[:len(hash)]),
conn: conn,
OnClose: func() {},
OnMessage: func(p Payload) {},
}
}
// Send message to this connection
func (c *Connection) Send(p Payload) {
if err := websocket.JSON.Send(c.conn, p); err != nil {
c.OnClose()
c.conn.Close()
//fmt.Println("[Error]", "Send message for ID", c.Id, err.Error())
} else {
}
}
// Connection polling
func (c *Connection) Poll() {
for {
var p Payload
if err := websocket.JSON.Receive(c.conn, &p); err == nil {
c.OnMessage(p)
} else {
c.OnClose()
c.conn.Close()
}
}
}