@@ -80,6 +80,7 @@ It holds all necessary information to make the package work internally.
80
80
*/
81
81
type Conn struct {
82
82
wsConn * websocket.Conn
83
+ wsConnOK bool
83
84
wsConnMutex sync.RWMutex
84
85
session * Session
85
86
listener map [string ]chan string
@@ -108,6 +109,7 @@ The goroutine for handling incoming messages is started
108
109
func NewConn (timeout time.Duration ) (* Conn , error ) {
109
110
wac := & Conn {
110
111
wsConn : nil , // will be set in connect()
112
+ wsConnOK : false ,
111
113
wsConnMutex : sync.RWMutex {},
112
114
listener : make (map [string ]chan string ),
113
115
listenerMutex : sync.RWMutex {},
@@ -135,7 +137,18 @@ func NewConn(timeout time.Duration) (*Conn, error) {
135
137
func (wac * Conn ) isConnected () bool {
136
138
wac .wsConnMutex .RLock ()
137
139
defer wac .wsConnMutex .RUnlock ()
138
- return wac .wsConn != nil
140
+ if wac .wsConn == nil {
141
+ return false
142
+ }
143
+ if wac .wsConnOK {
144
+ return true
145
+ }
146
+
147
+ // test connection by sending a ping. This might fail but we ignore that
148
+ wac .wsConn .WriteControl (websocket .PingMessage , []byte {}, time .Now ().Add (time .Second ))
149
+
150
+ // this method is expected to be called by loops. So we can just return false
151
+ return false
139
152
}
140
153
141
154
// connect should be guarded with wsConnMutex
@@ -152,6 +165,11 @@ func (wac *Conn) connect() error {
152
165
return fmt .Errorf ("couldn't dial whatsapp web websocket: %v" , err )
153
166
}
154
167
168
+ wsConn .SetPongHandler (func (appData string ) error {
169
+ wac .wsConnOK = true
170
+ return nil
171
+ })
172
+
155
173
wsConn .SetCloseHandler (func (code int , text string ) error {
156
174
fmt .Fprintf (os .Stderr , "websocket connection closed(%d, %s)\n " , code , text )
157
175
@@ -175,6 +193,7 @@ func (wac *Conn) connect() error {
175
193
func (wac * Conn ) reconnect () {
176
194
wac .wsConnMutex .Lock ()
177
195
wac .wsConn = nil
196
+ wac .wsConnOK = false
178
197
wac .wsConnMutex .Unlock ()
179
198
180
199
// wait up to 60 seconds and then reconnect. As writePump should send immediately, it might
@@ -259,6 +278,7 @@ func (wac *Conn) readPump() {
259
278
}
260
279
msgType , msg , err := wac .wsConn .ReadMessage ()
261
280
if err != nil {
281
+ wac .wsConnOK = false
262
282
if websocket .IsUnexpectedCloseError (err , websocket .CloseGoingAway ) {
263
283
wac .handle (fmt .Errorf ("unexpected websocket close: %v" , err ))
264
284
}
@@ -323,6 +343,7 @@ func (wac *Conn) writePump() {
323
343
}
324
344
if err := wac .wsConn .WriteMessage (msg .messageType , msg .data ); err != nil {
325
345
fmt .Fprintf (os .Stderr , "error writing to socket: %v\n " , err )
346
+ wac .wsConnOK = false
326
347
// add message to channel again to no loose it
327
348
go func () {
328
349
wac .writeChan <- msg
0 commit comments