forked from graarh/golang-socketio
-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.go
72 lines (58 loc) · 1.7 KB
/
client.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
package gosocketio
import (
"strconv"
_ "time"
"github.com/mtfelian/golang-socketio/transport"
)
const (
webSocketSchema = "ws://"
webSocketSecureSchema = "wss://"
socketioWebsocketURL = "/socket.io/?EIO=3&transport=websocket"
pollingSchema = "http://"
pollingSecureSchema = "https://"
socketioPollingURL = "/socket.io/?EIO=3&transport=polling"
)
// Client represents socket.io client
type Client struct {
*event
*Channel
}
// AddrWebsocket returns an url for socket.io connection for websocket transport
func AddrWebsocket(host string, port int, secure bool) string {
prefix := webSocketSchema
if secure {
prefix = webSocketSecureSchema
}
return prefix + host + ":" + strconv.Itoa(port) + socketioWebsocketURL
}
// AddrPolling returns an url for socket.io connection for polling transport
func AddrPolling(host string, port int, secure bool) string {
prefix := pollingSchema
if secure {
prefix = pollingSecureSchema
}
return prefix + host + ":" + strconv.Itoa(port) + socketioPollingURL
}
// Dial connects to server and initializes socket.io protocol
// The correct ws protocol addr example:
// ws://myserver.com/socket.io/?EIO=3&transport=websocket
func Dial(addr string, tr transport.Transport) (*Client, error) {
c := &Client{Channel: &Channel{}, event: &event{}}
c.Channel.init()
c.event.init()
var err error
c.conn, err = tr.Connect(addr)
if err != nil {
return nil, err
}
go c.Channel.inLoop(c.event)
go c.Channel.outLoop(c.event)
go c.Channel.pingLoop()
switch tr.(type) {
case *transport.PollingClientTransport:
go c.event.callHandler(c.Channel, OnConnection)
}
return c, nil
}
// Close client connection
func (c *Client) Close() { c.Channel.close(c.event) }