-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsconn.go
56 lines (47 loc) · 1.11 KB
/
wsconn.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
package mqtt
import (
"context"
"crypto/tls"
"io"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/srishina/mqtt.go/internal/mqttutil"
)
// WebsocketConn concrete implementation of Connection
// when used the MQTT client uses a WebSocket to
// connect to MQTT broker
type WebsocketConn struct {
conn *websocket.Conn
Host string
TLSConfig *tls.Config
rw io.ReadWriter
}
// BrokerURL the broker URL
func (w *WebsocketConn) BrokerURL() string {
return w.Host
}
// Connect connect to MQTT broker
func (w *WebsocketConn) Connect(ctx context.Context) (io.ReadWriter, error) {
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 10 * time.Second,
EnableCompression: false,
TLSClientConfig: w.TLSConfig,
Subprotocols: []string{"mqtt"},
}
ws, _, err := dialer.DialContext(ctx, w.Host, http.Header{})
if err != nil {
return nil, err
}
w.conn = ws
w.rw = mqttutil.NewWebsocketReadWriter(ws)
return w.rw, nil
}
// Close closes the connection
func (w *WebsocketConn) Close() {
if w.conn != nil {
w.conn.Close()
w.conn = nil
}
}