-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathcodec_sio.go
316 lines (261 loc) · 6.77 KB
/
codec_sio.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package socketio
import (
"bytes"
"fmt"
"io"
"json"
"os"
"strconv"
"utf8"
)
// The various delimiters used for framing in the socket.io protocol.
const (
SIOAnnotationRealm = "r"
SIOAnnotationJSON = "j"
sioMessageTypeDisconnect = 0
sioMessageTypeMessage = 1
sioMessageTypeHeartbeat = 2
sioMessageTypeHandshake = 3
)
var (
sioFrameDelim = []byte("~m~")
sioFrameDelimJSON = []byte("~j~")
sioFrameDelimHeartbeat = []byte("~h~")
)
// SioMessage fulfills the message interface.
type sioMessage struct {
annotations map[string]string
typ uint8
data []byte
}
// Type checks if the message starts with sioFrameDelimJSON or
// sioFrameDelimHeartbeat. If the prefix is something else, then the message
// is interpreted as a basic messageText.
func (sm *sioMessage) Type() uint8 {
switch sm.typ {
case sioMessageTypeMessage:
if _, ok := sm.Annotation(SIOAnnotationJSON); ok {
return MessageJSON
}
case sioMessageTypeDisconnect:
return MessageDisconnect
case sioMessageTypeHeartbeat:
return MessageHeartbeat
case sioMessageTypeHandshake:
return MessageHandshake
}
return MessageText
}
func (sm *sioMessage) Annotations() map[string]string {
return sm.annotations
}
func (sm *sioMessage) Annotation(key string) (value string, ok bool) {
if sm.annotations == nil {
return "", false
}
value, ok = sm.annotations[key]
return
}
// Heartbeat looks for a heartbeat value in the message. If a such value
// can be extracted, then that value and a true is returned. Otherwise a
// false will be returned.
func (sm *sioMessage) heartbeat() (heartbeat, bool) {
if sm.typ == sioMessageTypeHeartbeat {
if n, err := strconv.Atoi(string(sm.data)); err == nil {
return heartbeat(n), true
}
}
return -1, false
}
// Data returns the raw message as a string.
func (sm *sioMessage) Data() string {
return string(sm.data)
}
// Bytes returns the raw message.
func (sm *sioMessage) Bytes() []byte {
return sm.data
}
// JSON returns the JSON embedded in the message, if available.
func (sm *sioMessage) JSON() ([]byte, bool) {
if sm.Type() == MessageJSON {
return sm.data, true
}
return nil, false
}
// SIOCodec is the codec used by the official Socket.IO client by LearnBoost.
// Each message is framed with a prefix and goes like this:
// <DELIM>DATA-LENGTH<DELIM>[<OPTIONAL DELIM>]DATA.
type SIOCodec struct{}
type sioEncoder struct {
elem bytes.Buffer
}
func (sc SIOCodec) NewEncoder() Encoder {
return &sioEncoder{}
}
// Encode takes payload, encodes it and writes it to dst. Payload must be one
// of the following: a heartbeat, a handshake, []byte, string, int or anything
// than can be marshalled by the default json package. If payload can't be
// encoded or the writing fails, an error will be returned.
func (enc *sioEncoder) Encode(dst io.Writer, payload interface{}) (err os.Error) {
enc.elem.Reset()
switch t := payload.(type) {
case heartbeat:
s := strconv.Itoa(int(t))
_, err = fmt.Fprintf(dst, "%s%d%s%s%s", sioFrameDelim, len(s)+len(sioFrameDelimHeartbeat), sioFrameDelim, sioFrameDelimHeartbeat, s)
case handshake:
_, err = fmt.Fprintf(dst, "%s%d%s%s", sioFrameDelim, len(t), sioFrameDelim, t)
case []byte:
l := utf8.RuneCount(t)
if l == 0 {
break
}
_, err = fmt.Fprintf(dst, "%s%d%s%s", sioFrameDelim, l, sioFrameDelim, t)
case string:
l := utf8.RuneCountInString(t)
if l == 0 {
break
}
_, err = fmt.Fprintf(dst, "%s%d%s%s", sioFrameDelim, l, sioFrameDelim, t)
case int:
s := strconv.Itoa(t)
if s == "" {
break
}
_, err = fmt.Fprintf(dst, "%s%d%s%s", sioFrameDelim, len(s), sioFrameDelim, s)
default:
data, err := json.Marshal(payload)
if len(data) == 0 || err != nil {
break
}
err = json.Compact(&enc.elem, data)
if err != nil {
break
}
_, err = fmt.Fprintf(dst, "%s%d%s%s", sioFrameDelim, utf8.RuneCount(enc.elem.Bytes())+len(sioFrameDelimJSON), sioFrameDelim, sioFrameDelimJSON)
if err == nil {
_, err = enc.elem.WriteTo(dst)
}
}
return err
}
const (
sioDecodeStateBegin = iota
sioDecodeStateHeaderBegin
sioDecodeStateLength
sioDecodeStateHeaderEnd
sioDecodeStateData
sioDecodeStateEnd
)
type sioDecoder struct {
src *bytes.Buffer
buf bytes.Buffer
msg *sioMessage
key, value string
length, state int
}
func (sc SIOCodec) NewDecoder(src *bytes.Buffer) Decoder {
return &sioDecoder{
src: src,
state: sioDecodeStateBegin,
}
}
func (dec *sioDecoder) Reset() {
dec.buf.Reset()
dec.src.Reset()
dec.msg = nil
dec.state = sioDecodeStateBegin
dec.key = ""
dec.value = ""
dec.length = 0
}
func (dec *sioDecoder) Decode() (messages []Message, err os.Error) {
messages = make([]Message, 0, 1)
var c int
L:
for {
if dec.state == sioDecodeStateBegin {
dec.msg = &sioMessage{}
dec.state = sioDecodeStateHeaderBegin
dec.buf.Reset()
}
c, _, err = dec.src.ReadRune()
if err != nil {
break
}
switch dec.state {
case sioDecodeStateHeaderBegin:
dec.buf.WriteRune(c)
if dec.buf.Len() == len(sioFrameDelim) {
if !bytes.Equal(dec.buf.Bytes(), sioFrameDelim) {
dec.Reset()
return nil, os.NewError("Malformed header")
}
dec.state = sioDecodeStateLength
dec.buf.Reset()
}
continue
case sioDecodeStateLength:
if c >= '0' && c <= '9' {
dec.buf.WriteRune(c)
continue
}
if dec.length, err = strconv.Atoi(dec.buf.String()); err != nil {
dec.Reset()
return nil, err
}
dec.buf.Reset()
dec.state = sioDecodeStateHeaderEnd
fallthrough
case sioDecodeStateHeaderEnd:
dec.buf.WriteRune(c)
if dec.buf.Len() < len(sioFrameDelim) {
continue
}
if !bytes.Equal(dec.buf.Bytes(), sioFrameDelim) {
dec.Reset()
return nil, os.NewError("Malformed header")
}
dec.state = sioDecodeStateData
dec.buf.Reset()
if dec.length > 0 {
continue
}
fallthrough
case sioDecodeStateData:
if dec.length > 0 {
dec.buf.WriteRune(c)
dec.length--
utf8str := utf8.NewString(dec.src.String())
if utf8str.RuneCount() >= dec.length {
str := utf8str.Slice(0, dec.length)
dec.buf.WriteString(str)
dec.src.Next(len(str))
dec.length = 0
} else {
break L
}
}
data := dec.buf.Bytes()
dec.msg.typ = sioMessageTypeMessage
if bytes.HasPrefix(data, sioFrameDelimJSON) {
dec.msg.annotations = make(map[string]string)
dec.msg.annotations[SIOAnnotationJSON] = ""
data = data[len(sioFrameDelimJSON):]
} else if bytes.HasPrefix(data, sioFrameDelimHeartbeat) {
dec.msg.typ = sioMessageTypeHeartbeat
data = data[len(sioFrameDelimHeartbeat):]
}
dec.msg.data = make([]byte, len(data))
copy(dec.msg.data, data)
messages = append(messages, dec.msg)
dec.state = sioDecodeStateBegin
dec.buf.Reset()
continue
}
dec.buf.WriteRune(c)
}
if err == os.EOF {
err = nil
}
return
}