-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhandlers_transmission.go
74 lines (59 loc) · 1.72 KB
/
handlers_transmission.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
package server
import (
"errors"
"github.com/muka/peerjs-go/models"
)
//NewTransmissionHandler handles transmission of messages
func NewTransmissionHandler(realm IRealm, opts Options) func(client IClient, message models.IMessage) bool {
var handle func(client IClient, message models.IMessage) bool
handle = func(client IClient, message models.IMessage) bool {
clientID := "<no-id>"
if client != nil {
clientID = client.GetID()
}
log := createLogger("client:"+clientID, opts)
mtype := message.GetType()
srcID := message.GetSrc()
dstID := message.GetDst()
destinationClient := realm.GetClientByID(dstID)
// User is connected!
if destinationClient != nil {
socket := destinationClient.GetSocket()
var err error
if socket != nil {
err = socket.WriteJSON(message)
} else {
err = errors.New("Peer dead")
}
if err != nil {
// This happens when a peer disconnects without closing connections and
// the associated WebSocket has not closed.
// Tell other side to stop trying.
log.Warnf("Error: %s", err)
if socket != nil {
socket.Close()
} else {
realm.RemoveClientByID(destinationClient.GetID())
}
handle(client, models.Message{
Type: MessageTypeLeave,
Src: dstID,
Dst: srcID,
})
}
} else {
// Wait for this client to connect/reconnect (XHR) for important
// messages.
if (mtype != MessageTypeLeave && mtype != MessageTypeExpire) && dstID != "" {
realm.AddMessageToQueue(dstID, message)
} else if mtype == MessageTypeLeave && dstID == "" {
realm.RemoveClientByID(srcID)
} else {
// Unavailable destination specified with message LEAVE or EXPIRE
// Ignore
}
}
return true
}
return handle
}