-
Notifications
You must be signed in to change notification settings - Fork 26
/
socket.go
78 lines (65 loc) · 1.73 KB
/
socket.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 socketio implements a client for SocketIO protocol
// as specified in https://github.com/LearnBoost/socket.io-spec
package socketio
import (
"time"
)
type Socket struct {
URL string
Session *Session
Transport transport
}
// Dial opens a new client connection to the socket.io server then connects
// to the given channel.
func DialAndConnect(url string, channel string, query string) (*Socket, error) {
socket, err := Dial(url)
if err != nil {
return nil, err
}
endpoint := NewEndpoint(channel, query)
connectMsg := NewConnect(endpoint)
socket.Send(connectMsg)
return socket, nil
}
// Dial opens a new client connection to the socket.io server using one of
// the implemented and supported Transports.
func Dial(url string) (*Socket, error) {
session, err := NewSession(url)
if err != nil {
return nil, err
}
transport, err := newTransport(session, url)
if err != nil {
return nil, err
}
// Heartbeat goroutine
go func() {
heartbeatMsg := NewHeartbeat()
for {
time.Sleep(session.HeartbeatTimeout - time.Second)
err := transport.Send(heartbeatMsg.String())
if err != nil {
return
}
}
}()
return &Socket{url, session, transport}, nil
}
// Receive receives the raw message from the underlying transport and
// converts it to the Message type.
func (socket *Socket) Receive() (*Message, error) {
rawMsg, err := socket.Transport.Receive()
if err != nil {
return nil, err
}
return parseMessage(rawMsg)
}
// Send sends the given Message to the socket.io server using it's
// underlying transport.
func (socket *Socket) Send(msg *Message) error {
return socket.Transport.Send(msg.String())
}
// Close underlying transport
func (socket *Socket) Close() error {
return socket.Transport.Close()
}