Проблемы: - signal_handler блокировал shutdown() - Порт не освобождался после Ctrl+C - Невозможно было перезапустить сервер Решения: - Убран signal_handler — используется KeyboardInterrupt - shutdown() вызывается в отдельном потоке (avoid deadlock) - with контекст для автоматического закрытия - allow_reuse_address = True для быстрого рестарта - Обработка OSError при занятом порте
92 lines
3.2 KiB
Python
Executable File
92 lines
3.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Simple HTTP server for WebSocket client testing.
|
|
|
|
Usage:
|
|
python3 start_web_server.py [--port PORT]
|
|
|
|
Open in browser:
|
|
http://localhost:PORT/client.html
|
|
"""
|
|
|
|
import argparse
|
|
import http.server
|
|
import socketserver
|
|
import os
|
|
import sys
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
PORT = 8080
|
|
SCRIPT_DIR = Path(__file__).parent.resolve()
|
|
|
|
|
|
class CustomHandler(http.server.SimpleHTTPRequestHandler):
|
|
"""Custom handler with better logging."""
|
|
|
|
def do_GET(self):
|
|
super().do_GET()
|
|
print(f"[WebServer] ✅ {self.requestline} → {self.command} {self.path}")
|
|
|
|
def log_message(self, format, *args):
|
|
# Suppress default logging
|
|
pass
|
|
|
|
|
|
class ReusableTCPServer(socketserver.TCPServer):
|
|
"""TCP Server with address reuse enabled."""
|
|
allow_reuse_address = True
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='WebSocket Client Web Server')
|
|
parser.add_argument('--port', type=int, default=PORT, help=f'Port (default: {PORT})')
|
|
parser.add_argument('--host', default='0.0.0.0', help='Host (default: 0.0.0.0)')
|
|
args = parser.parse_args()
|
|
|
|
# Change to script directory
|
|
os.chdir(SCRIPT_DIR)
|
|
|
|
print(f"""
|
|
╔══════════════════════════════════════════════════════════╗
|
|
║ 🛰️ Wyoming Satellite WebSocket Client Server ║
|
|
╠══════════════════════════════════════════════════════════╣
|
|
║ Serving: {str(SCRIPT_DIR):<45} ║
|
|
║ URL: http://localhost:{args.port:<36} ║
|
|
║ Remote: http://<your-ip>:{args.port:<32} ║
|
|
║ ║
|
|
║ Press Ctrl+C to stop ║
|
|
╚══════════════════════════════════════════════════════════╝
|
|
""")
|
|
|
|
try:
|
|
with ReusableTCPServer((args.host, args.port), CustomHandler) as httpd:
|
|
print(f"🚀 Server started on http://{args.host}:{args.port}")
|
|
print("📖 Serving files from:", SCRIPT_DIR)
|
|
print("\n⌨️ Press Ctrl+C to stop\n")
|
|
|
|
try:
|
|
httpd.serve_forever()
|
|
except KeyboardInterrupt:
|
|
print("\n👋 Shutting down gracefully...")
|
|
# Shutdown in a separate thread to avoid deadlock
|
|
shutdown_thread = threading.Thread(target=httpd.shutdown)
|
|
shutdown_thread.start()
|
|
shutdown_thread.join(timeout=2)
|
|
httpd.server_close()
|
|
print("✅ Server stopped successfully")
|
|
|
|
except OSError as e:
|
|
print(f"\n❌ Error: Could not bind to port {args.port}")
|
|
print(f" {e}")
|
|
print("\n💡 Try using a different port:")
|
|
print(f" python3 {sys.argv[0]} --port 8081\n")
|
|
sys.exit(1)
|
|
except Exception as e:
|
|
print(f"\n❌ Unexpected error: {e}")
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|