-
Notifications
You must be signed in to change notification settings - Fork 260
/
send.go
87 lines (72 loc) · 1.58 KB
/
send.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
package gosocketio
import (
"encoding/json"
"errors"
"github.com/graarh/golang-socketio/protocol"
"log"
"time"
)
var (
ErrorSendTimeout = errors.New("Timeout")
ErrorSocketOverflood = errors.New("Socket overflood")
)
/**
Send message packet to socket
*/
func send(msg *protocol.Message, c *Channel, args interface{}) error {
//preventing json/encoding "index out of range" panic
defer func() {
if r := recover(); r != nil {
log.Println("socket.io send panic: ", r)
}
}()
if args != nil {
json, err := json.Marshal(&args)
if err != nil {
return err
}
msg.Args = string(json)
}
command, err := protocol.Encode(msg)
if err != nil {
return err
}
if len(c.out) == queueBufferSize {
return ErrorSocketOverflood
}
c.out <- command
return nil
}
/**
Create packet based on given data and send it
*/
func (c *Channel) Emit(method string, args interface{}) error {
msg := &protocol.Message{
Type: protocol.MessageTypeEmit,
Method: method,
}
return send(msg, c, args)
}
/**
Create ack packet based on given data and send it and receive response
*/
func (c *Channel) Ack(method string, args interface{}, timeout time.Duration) (string, error) {
msg := &protocol.Message{
Type: protocol.MessageTypeAckRequest,
AckId: c.ack.getNextId(),
Method: method,
}
waiter := make(chan string)
c.ack.addWaiter(msg.AckId, waiter)
err := send(msg, c, args)
if err != nil {
c.ack.removeWaiter(msg.AckId)
}
select {
case result := <-waiter:
return result, nil
case <-time.After(timeout):
c.ack.removeWaiter(msg.AckId)
return "", ErrorSendTimeout
}
}