Improve asyncio usage in telnet server

This commit is contained in:
Ian Renton
2026-09-11 21:38:22 +01:00
parent e3df512b9e
commit 4a09e46fe0
9 changed files with 55 additions and 45 deletions
+35 -25
View File
@@ -21,21 +21,16 @@ class TelnetServer:
self._running = False
self._clients = set()
self._loop = None
self._shutdown_event = asyncio.Event()
def start(self, port=7373):
"""Starts the telnet server"""
self._port = port
# Start telnet server on the async loop
def run_loop():
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._loop.run_until_complete(self._start_internal())
self._loop.run_forever()
# Start the network thread as a daemon so it exits cleanly when the main script stops
t = threading.Thread(target=run_loop, daemon=True)
# Start the telnet server. asyncio.run() needs a coroutine, and threading.Thread needs a plain callable, so
# hand Thread the bridge between the two directly rather than writing a one-line wrapper method for it.
t = threading.Thread(target=asyncio.run, args=(self._start_internal(),), name="TelnetServer", daemon=True)
t.start()
logger.debug("Telnet server background thread spawned")
@@ -44,8 +39,16 @@ class TelnetServer:
self._running = True
async def _start_internal(self):
"""Start method (async). Sets up the telnet server and waits for shutdown."""
self._loop = asyncio.get_running_loop()
server = await asyncio.start_server(self._handle_client, "0.0.0.0", self._port)
logger.info(f"Telnet server listening on port {self._port}")
await asyncio.start_server(self._handle_client, "0.0.0.0", self._port)
async with server:
await self._shutdown_event.wait()
await self._stop_internal()
async def _handle_client(self, reader, writer):
"""Handles a new client connection"""
@@ -73,26 +76,13 @@ class TelnetServer:
if not data:
break
text = data.decode("ascii", errors="ignore")
for char in text:
if char in ("\r", "\n"):
# User pressed Enter, evaluate the command
command = input_buffer.strip().lower()
input_buffer = ""
input_buffer, command = self._consume_input(input_buffer, data)
if command == "exit":
writer.write(b"Goodbye!\r\n")
await writer.drain()
# Exit the while read loop, this will disconnect the client.
return
elif char in ("\b", "\x7f"):
# Handle backspaces
input_buffer = input_buffer[:-1]
else:
input_buffer += char
except asyncio.CancelledError:
pass
except Exception:
@@ -106,9 +96,10 @@ class TelnetServer:
def stop(self):
"""Stops the telnet server"""
self._running = False
if self._loop and self._loop.is_running():
logger.debug("Stopping telnet server...")
self._loop.call_soon_threadsafe(self._loop.stop)
self._loop.call_soon_threadsafe(self._shutdown_event.set)
async def _stop_internal(self):
"""Stops the telnet server"""
@@ -146,6 +137,25 @@ class TelnetServer:
for writer in disconnected_clients:
self._clients.discard(writer)
@staticmethod
def _consume_input(input_buffer: str, data: bytes) -> tuple[str, str | None]:
"""Handle any input the user gives us, keeping a rolling buffer that we keep passing back through and
adding to. Once we get a command, return that as well, so the caller can deal with it."""
command = None
for char in data.decode("ascii", errors="ignore"):
if char in ("\r", "\n"):
stripped = input_buffer.strip().lower()
if stripped:
command = stripped
input_buffer = ""
elif char in ("\b", "\x7f"):
# Handle backspaces
input_buffer = input_buffer[:-1]
else:
input_buffer += char
return input_buffer, command
@staticmethod
def _format_dxspider_spot(spot: Spot) -> str:
"""Formats a spot into the format DXspider uses:
+1 -1
View File
@@ -77,7 +77,7 @@
</div>
<script src="/static/js/add-spot.js?v=1789140190"></script>
<script src="/static/js/add-spot.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-add-spot").addClass("active");
}); <!-- highlight active page in nav --></script>
+1 -1
View File
@@ -83,7 +83,7 @@
</div>
<script src="/static/js/alerts.js?v=1789140190"></script>
<script src="/static/js/alerts.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-alerts").addClass("active");
}); <!-- highlight active page in nav --></script>
+2 -2
View File
@@ -76,8 +76,8 @@
</div>
<script src="/static/js/spotsbandsandmap.js?v=1789140190"></script>
<script src="/static/js/bands.js?v=1789140190"></script>
<script src="/static/js/spotsbandsandmap.js?v=1789159102"></script>
<script src="/static/js/bands.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-bands").addClass("active");
}); <!-- highlight active page in nav --></script>
+5 -5
View File
@@ -1,6 +1,6 @@
{% extends "skeleton.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/css/style.css?v=1789140190" type="text/css">
<link rel="stylesheet" href="/static/css/style.css?v=1789159102" type="text/css">
<link href="/static/vendor/css/bootstrap-5.3.8.min.css" rel="stylesheet">
<link href="/static/vendor/css/fontawesome-6.7.2.min.css" rel="stylesheet">
<link href="/static/vendor/css/solid-6.7.2.min.css" rel="stylesheet">
@@ -16,10 +16,10 @@
window.fetchEventSource = fetchEventSource;
</script>
<script src="/static/js/utils.js?v=1789140190"></script>
<script src="/static/js/ui-ham.js?v=1789140190"></script>
<script src="/static/js/geo.js?v=1789140190"></script>
<script src="/static/js/common.js?v=1789140190"></script>
<script src="/static/js/utils.js?v=1789159102"></script>
<script src="/static/js/ui-ham.js?v=1789159102"></script>
<script src="/static/js/geo.js?v=1789159102"></script>
<script src="/static/js/common.js?v=1789159102"></script>
{% end %}
{% block body %}
<div class="container">
+1 -1
View File
@@ -284,7 +284,7 @@
</div>
<script src="/static/vendor/js/chart-4.4.9.umd.min.js"></script>
<script src="/static/js/conditions.js?v=1789140190"></script>
<script src="/static/js/conditions.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-conditions").addClass("active");
}); <!-- highlight active page in nav --></script>
+2 -2
View File
@@ -113,8 +113,8 @@
const CARTODB_API_KEY = "{{ web_ui_options.get('cartodb_api_key', '') }}";
</script>
<script src="/static/js/spotsbandsandmap.js?v=1789140190"></script>
<script src="/static/js/map.js?v=1789140190"></script>
<script src="/static/js/spotsbandsandmap.js?v=1789159102"></script>
<script src="/static/js/map.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-map").addClass("active");
}); <!-- highlight active page in nav --></script>
+2 -2
View File
@@ -125,8 +125,8 @@
</div>
<script src="/static/js/spotsbandsandmap.js?v=1789140190"></script>
<script src="/static/js/spots.js?v=1789140190"></script>
<script src="/static/js/spotsbandsandmap.js?v=1789159102"></script>
<script src="/static/js/spots.js?v=1789159102"></script>
<script>$(document).ready(function () {
$("#nav-link-spots").addClass("active");
}); <!-- highlight active page in nav --></script>
+1 -1
View File
@@ -86,7 +86,7 @@
</div>
</div>
<script src="/static/js/status.js?v=1789140190"></script>
<script src="/static/js/status.js?v=1789159102"></script>
<script>
$(document).ready(function () {
$("#nav-link-status").addClass("active");