Skip to content

Commit a5caf38

Browse files
authored
Merge pull request #4 from CodeShellDev/main
wait for client
2 parents 2660bc5 + 6d26e04 commit a5caf38

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

internals/server/http.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,12 @@ func httpHandler(w http.ResponseWriter, req *http.Request) {
4343
w.Header().Set("Content-Type", "application/json")
4444
json.NewEncoder(w).Encode(resp)
4545

46-
client := getClient(clientID)
46+
client, err := WaitForClient(clientID, time.Duration(15 * time.Second))
47+
48+
if err != nil {
49+
logger.Error("Could not get client: ", err.Error())
50+
return
51+
}
4752

4853
reachable, err := tryPing(client, body.IP,
4954
func() (bool, error) {

internals/server/websocket.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package server
22

33
import (
4+
"errors"
45
"net/http"
56
"sync"
67
"time"
@@ -61,6 +62,24 @@ func getClient(id string) *websocket.Conn {
6162
return clients[id]
6263
}
6364

65+
func WaitForClient(clientID string, timeout time.Duration) (*websocket.Conn, error) {
66+
deadline := time.Now().Add(timeout)
67+
68+
for time.Now().Before(deadline) {
69+
clientsMutex.Lock()
70+
conn, exists := clients[clientID]
71+
clientsMutex.Unlock()
72+
73+
if exists && conn != nil {
74+
return conn, nil
75+
}
76+
77+
time.Sleep(100 * time.Millisecond)
78+
}
79+
80+
return nil, errors.New("Timed out waiting for client")
81+
}
82+
6483
func sendToClient(client *websocket.Conn, data map[string]any) error {
6584
return client.WriteJSON(data)
6685
}

0 commit comments

Comments
 (0)