golang-socketio/client.go

67 lines
1.2 KiB
Go
Raw Normal View History

2016-05-18 22:11:10 +02:00
package gosocketio
import (
2016-05-18 22:55:49 +02:00
"github.com/graarh/golang-socketio/transport"
"strconv"
2016-05-18 22:11:10 +02:00
)
const (
webSocketProtocol = "ws://"
webSocketSecureProtocol = "wss://"
2016-05-18 22:11:10 +02:00
socketioUrl = "/socket.io/?EIO=3&transport=websocket"
)
/**
Socket.io client representation
*/
type Client struct {
methods
Channel
}
/**
Get ws/wss url by host and port
*/
func GetUrl(host string, port int, secure bool) string {
var prefix string
if secure {
prefix = webSocketSecureProtocol
} else {
prefix = webSocketProtocol
}
return prefix + host + ":" + strconv.Itoa(port) + socketioUrl
}
2016-05-18 22:11:10 +02:00
/**
connect to host and initialise socket.io protocol
The correct ws protocol url example:
ws://myserver.com/socket.io/?EIO=3&transport=websocket
You can use GetUrlByHost for generating correct url
2016-05-18 22:11:10 +02:00
*/
func Dial(url string, tr transport.Transport) (*Client, error) {
2016-05-18 22:11:10 +02:00
c := &Client{}
c.initChannel()
c.initMethods()
var err error
c.conn, err = tr.Connect(url)
2016-05-18 22:11:10 +02:00
if err != nil {
return nil, err
}
go inLoop(&c.Channel, &c.methods)
go outLoop(&c.Channel, &c.methods)
go pinger(&c.Channel)
return c, nil
}
/**
Close client connection
*/
func (c *Client) Close() {
CloseChannel(&c.Channel, &c.methods)
}