@@ -34,6 +34,8 @@ func (b *Bot) HandleWS(w http.ResponseWriter, r *http.Request) {
3434 if err != nil {
3535 return
3636 }
37+ // This ensures that when this function exits, the socket is closed.
38+ // Closing the socket will also force the "Command Reader" goroutine to exit.
3739 defer conn .Close ()
3840
3941 // --- 1. THE COMMAND READER (Browser -> Go) ---
@@ -57,28 +59,36 @@ func (b *Bot) HandleWS(w http.ResponseWriter, r *http.Request) {
5759 }()
5860
5961 // --- 2. THE STATE WRITER (Go -> Browser) ---
60- // Stream updates every 100ms
62+ ticker := time .NewTicker (100 * time .Millisecond )
63+ defer ticker .Stop ()
64+
6165 for {
62- // Create a snapshot from your current bot fields
63- snap := BotSnapshot {
64- FishingEnabled : b .fishingEnabled ,
65- Name : b .state .CaptureFrame ().Player .Name ,
66- X : b .state .CaptureFrame ().Player .Pos .X ,
67- Y : b .state .CaptureFrame ().Player .Pos .Y ,
68- Z : b .state .CaptureFrame ().Player .Pos .Z ,
69- Waypoints : []Waypoint {
70- {ID : "wp-1" , Type : "Walk" , X : 32345 , Y : 32222 , Z : 7 },
71- {ID : "wp-2" , Type : "Walk" , X : 32350 , Y : 32230 , Z : 7 },
72- {ID : "wp-3" , Type : "Rope" , X : 32350 , Y : 32230 , Z : 7 },
73- {ID : "wp-4" , Type : "Walk" , X : 32352 , Y : 32235 , Z : 6 },
74- },
75- }
66+ select {
67+ // EXIT if the Bot is stopped via Stop()
68+ case <- b .stopChan :
69+ return
7670
77- payload , _ := json .Marshal (snap )
78- if err := conn .WriteMessage (websocket .TextMessage , payload ); err != nil {
79- break
80- }
71+ // EXECUTE update every tick
72+ case <- ticker .C :
73+ snap := BotSnapshot {
74+ FishingEnabled : b .fishingEnabled ,
75+ Name : b .state .CaptureFrame ().Player .Name ,
76+ X : b .state .CaptureFrame ().Player .Pos .X ,
77+ Y : b .state .CaptureFrame ().Player .Pos .Y ,
78+ Z : b .state .CaptureFrame ().Player .Pos .Z ,
79+ Waypoints : []Waypoint {
80+ {ID : "wp-1" , Type : "Walk" , X : 32345 , Y : 32222 , Z : 7 },
81+ {ID : "wp-2" , Type : "Walk" , X : 32350 , Y : 32230 , Z : 7 },
82+ {ID : "wp-3" , Type : "Rope" , X : 32350 , Y : 32230 , Z : 7 },
83+ {ID : "wp-4" , Type : "Walk" , X : 32352 , Y : 32235 , Z : 6 },
84+ },
85+ }
8186
82- time .Sleep (100 * time .Millisecond )
87+ // We use WriteJSON directly to simplify the code
88+ if err := conn .WriteJSON (snap ); err != nil {
89+ // If the browser tab is closed, this will error out and exit the loop
90+ return
91+ }
92+ }
8393 }
8494}
0 commit comments