da03 commited on
Commit
c1c036e
·
1 Parent(s): 3f1526b
Files changed (2) hide show
  1. main.py +23 -2
  2. static/index.html +33 -8
main.py CHANGED
@@ -537,8 +537,18 @@ async def websocket_endpoint(websocket: WebSocket):
537
 
538
  # Send the generated frame back to the client
539
  print(f"[{time.perf_counter():.3f}] Sending image to client...")
540
- await websocket.send_json({"image": img_str})
541
- print(f"[{time.perf_counter():.3f}] Image sent. Queue size before next_input: {input_queue.qsize()}")
 
 
 
 
 
 
 
 
 
 
542
 
543
  # Log the input
544
  log_interaction(client_id, data, generated_frame=sample_img)
@@ -559,6 +569,12 @@ async def websocket_endpoint(websocket: WebSocket):
559
  is_processing = False
560
  return
561
 
 
 
 
 
 
 
562
  #if is_processing:
563
  # print(f"[{current_time:.3f}] Already processing an input. Will check again later.")
564
  # return
@@ -657,6 +673,11 @@ async def websocket_endpoint(websocket: WebSocket):
657
  await input_queue.put(data)
658
  print(f"[{receive_time:.3f}] Received input. Queue size now: {input_queue.qsize()}")
659
 
 
 
 
 
 
660
  # If we're not currently processing, start processing this input
661
  if not is_processing:
662
  print(f"[{receive_time:.3f}] Not currently processing, will call process_next_input()")
 
537
 
538
  # Send the generated frame back to the client
539
  print(f"[{time.perf_counter():.3f}] Sending image to client...")
540
+ try:
541
+ await websocket.send_json({"image": img_str})
542
+ print(f"[{time.perf_counter():.3f}] Image sent. Queue size before next_input: {input_queue.qsize()}")
543
+ except RuntimeError as e:
544
+ if "Cannot call 'send' once a close message has been sent" in str(e):
545
+ print(f"[{time.perf_counter():.3f}] WebSocket closed, skipping image send")
546
+ break
547
+ else:
548
+ raise e
549
+ except Exception as e:
550
+ print(f"[{time.perf_counter():.3f}] Error sending image: {e}")
551
+ break
552
 
553
  # Log the input
554
  log_interaction(client_id, data, generated_frame=sample_img)
 
569
  is_processing = False
570
  return
571
 
572
+ # Check if WebSocket is still open by checking if it's in a closed state
573
+ if websocket.client_state.value >= 2: # CLOSING or CLOSED
574
+ print(f"[{current_time:.3f}] WebSocket in closed state ({websocket.client_state.value}), stopping processing")
575
+ is_processing = False
576
+ return
577
+
578
  #if is_processing:
579
  # print(f"[{current_time:.3f}] Already processing an input. Will check again later.")
580
  # return
 
673
  await input_queue.put(data)
674
  print(f"[{receive_time:.3f}] Received input. Queue size now: {input_queue.qsize()}")
675
 
676
+ # Check if WebSocket is still open before processing
677
+ if websocket.client_state.value >= 2: # CLOSING or CLOSED
678
+ print(f"[{receive_time:.3f}] WebSocket closed, skipping processing")
679
+ continue
680
+
681
  # If we're not currently processing, start processing this input
682
  if not is_processing:
683
  print(f"[{receive_time:.3f}] Not currently processing, will call process_next_input()")
static/index.html CHANGED
@@ -93,7 +93,7 @@
93
  <div class="canvas-container">
94
  <div id="timeoutWarning" class="alert alert-warning" style="display: none; margin-bottom: 15px;">
95
  <strong>Connection Timeout Warning:</strong>
96
- No user activity detected. Connection will be dropped in <span id="timeoutCountdown">10</span> seconds.
97
  <button type="button" class="btn btn-sm btn-primary ms-2" onclick="resetTimeout()">Stay Connected</button>
98
  </div>
99
 
@@ -190,11 +190,24 @@
190
 
191
  socket.onclose = function(event) {
192
  console.log("WebSocket connection closed. Attempting to reconnect...");
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  isConnected = false;
194
  stopAutoInput(); // Stop auto-input when connection is lost
195
  stopTimeoutCountdown(); // Stop timeout countdown when connection is lost
196
- clearInterval(heartbeatInterval);
197
- scheduleReconnection();
198
  };
199
 
200
  socket.onerror = function(error) {
@@ -387,8 +400,12 @@
387
  }
388
 
389
  if (timeoutCountdown <= 0) {
 
390
  stopTimeoutCountdown();
391
- console.log("Connection timeout countdown finished");
 
 
 
392
  }
393
  }, 1000);
394
  }
@@ -416,12 +433,20 @@
416
  }
417
 
418
  function resetTimeout() {
419
- // Send a heartbeat to reset the server's timeout
420
- if (socket && socket.readyState === WebSocket.OPEN) {
421
  try {
422
- socket.send(JSON.stringify({ type: "heartbeat" }));
 
 
 
 
 
 
 
 
423
  } catch (error) {
424
- console.error("Error sending heartbeat:", error);
425
  }
426
  }
427
  stopTimeoutCountdown();
 
93
  <div class="canvas-container">
94
  <div id="timeoutWarning" class="alert alert-warning" style="display: none; margin-bottom: 15px;">
95
  <strong>Connection Timeout Warning:</strong>
96
+ No user activity detected. Connection will be dropped in <span id="timeoutCountdown">10</span> seconds and page will refresh automatically.
97
  <button type="button" class="btn btn-sm btn-primary ms-2" onclick="resetTimeout()">Stay Connected</button>
98
  </div>
99
 
 
190
 
191
  socket.onclose = function(event) {
192
  console.log("WebSocket connection closed. Attempting to reconnect...");
193
+ console.log("Close event code:", event.code, "reason:", event.reason);
194
+
195
+ // Check if this was a timeout closure
196
+ if (event.code === 1000 && event.reason === "User inactivity timeout") {
197
+ console.log("Connection closed due to timeout - refreshing page");
198
+ stopAutoInput(); // Stop auto-input when connection is lost
199
+ stopTimeoutCountdown(); // Stop timeout countdown when connection is lost
200
+ //clearInterval(heartbeatInterval);
201
+ // Refresh the page to reconnect
202
+ window.location.reload();
203
+ return;
204
+ }
205
+
206
  isConnected = false;
207
  stopAutoInput(); // Stop auto-input when connection is lost
208
  stopTimeoutCountdown(); // Stop timeout countdown when connection is lost
209
+ //clearInterval(heartbeatInterval);
210
+ //scheduleReconnection();
211
  };
212
 
213
  socket.onerror = function(error) {
 
400
  }
401
 
402
  if (timeoutCountdown <= 0) {
403
+ stopAutoInput();
404
  stopTimeoutCountdown();
405
+ //clearInterval(heartbeatInterval);
406
+ console.log("Connection timeout countdown finished - refreshing page");
407
+ // Refresh the page to reconnect
408
+ window.location.reload();
409
  }
410
  }, 1000);
411
  }
 
433
  }
434
 
435
  function resetTimeout() {
436
+ // Send a regular input to reset the server's timeout
437
+ if (socket && socket.readyState === WebSocket.OPEN && lastSentPosition) {
438
  try {
439
+ socket.send(JSON.stringify({
440
+ "x": lastSentPosition.x,
441
+ "y": lastSentPosition.y,
442
+ "is_left_click": false,
443
+ "is_right_click": false,
444
+ "keys_down": [],
445
+ "keys_up": []
446
+ }));
447
+ updateLastUserInputTime(); // Update for auto-input mechanism
448
  } catch (error) {
449
+ console.error("Error sending timeout reset input:", error);
450
  }
451
  }
452
  stopTimeoutCountdown();