Bladeren bron

【重构】

PJ-568 2 jaren geleden
bovenliggende
commit
e507ead1f6
7 gewijzigde bestanden met toevoegingen van 353 en 446 verwijderingen
  1. 61 0
      html-chat.css
  2. 5 157
      index.html
  3. 117 0
      index.html.bak
  4. 0 91
      new_chat.html
  5. 0 89
      new_index.html
  6. 168 108
      server.py
  7. 2 1
      需求.md

+ 61 - 0
html-chat.css

@@ -0,0 +1,61 @@
+body {
+    font-family: Arial, sans-serif;
+    background-color: #f4f4f4;
+    margin: 0;
+    padding: 0;
+    color: #333;
+}
+
+.container {
+    width: 80%;
+    max-width: 600px;
+    margin: 20px auto;
+    padding: 20px;
+    background-color: #fff;
+    border: 1px solid #ccc;
+    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
+    border-radius: 5px;
+    /* IE9+ */
+}
+
+fieldset {
+    border: 1px solid #ddd;
+    padding: 10px;
+    margin-bottom: 5px;
+}
+
+legend {
+    font-weight: bold;
+    padding: 0 10px;
+}
+
+label {
+    display: block;
+    margin-bottom: 5px;
+}
+
+input[type="text"],
+textarea {
+    box-sizing: border-box;
+    max-width: 100%;
+    width: 100%;
+    padding: 8px;
+    margin-bottom: 10px;
+    border: 1px solid #ddd;
+    border-radius: 3px;
+    /* IE9+ */
+}
+
+button {
+    padding: 8px 15px;
+    background-color: #007BFF;
+    color: #fff;
+    border: none;
+    border-radius: 3px;
+    /* IE9+ */
+    cursor: pointer;
+}
+
+button:hover {
+    background-color: #0056b3;
+}

+ 5 - 157
index.html

@@ -4,176 +4,24 @@
 <head>
     <meta charset="UTF-8">
     <title>聊天室</title>
-    <script>
-        // Polyfill for IE9 and below to support addEventListener
-        if (!Element.prototype.addEventListener) {
-            Element.prototype.addEventListener = function (eventName, callback) {
-                this.attachEvent('on' + eventName, callback);
-            };
-        }
-
-        // Polyfill for IE9 and below to support removeEventListener
-        if (!Element.prototype.removeEventListener) {
-            Element.prototype.removeEventListener = function (eventName, callback) {
-                this.detachEvent('on' + eventName, callback);
-            };
-        }
-    </script>
-    <style>
-        body {
-            font-family: Arial, sans-serif;
-            background-color: #f4f4f4;
-            margin: 0;
-            padding: 0;
-            color: #333;
-        }
-
-        .container {
-            width: 80%;
-            max-width: 600px;
-            margin: 20px auto;
-            padding: 20px;
-            background-color: #fff;
-            border: 1px solid #ccc;
-            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
-            border-radius: 5px;
-            /* IE9+ */
-        }
-
-        fieldset {
-            border: 1px solid #ddd;
-            padding: 10px;
-            margin-bottom: 5px;
-        }
-
-        legend {
-            font-weight: bold;
-            padding: 0 10px;
-        }
-
-        label {
-            display: block;
-            margin-bottom: 5px;
-        }
-
-        input[type="text"],
-        textarea {
-            box-sizing: border-box;
-            max-width: 100%;
-            width: 100%;
-            padding: 8px;
-            margin-bottom: 10px;
-            border: 1px solid #ddd;
-            border-radius: 3px;
-            /* IE9+ */
-        }
-
-        button {
-            padding: 8px 15px;
-            background-color: #007BFF;
-            color: #fff;
-            border: none;
-            border-radius: 3px;
-            /* IE9+ */
-            cursor: pointer;
-        }
-
-        button:hover {
-            background-color: #0056b3;
-        }
-    </style>
+    <link type="text/css" rel="stylesheet" href="html-chat.css">
 </head>
 
 <body>
     <div class="container">
-        <form id="roomForm">
+        <form action="/chat" method="get">
             <fieldset>
                 <legend>主页</legend>
-                <label for="nickname">昵称:</label>
+                <label for="nickname">昵称</label>
                 <input type="text" id="nickname" name="nickname" value="匿名">
                 <br>
-                <label for="roomId">房间号:</label>
-                <input type="text" id="roomId" name="roomId">
+                <label for="roomid">房间号:</label>
+                <input type="text" id="roomid" name="roomid" value="默认">
                 <br>
                 <button type="submit">进入聊天室</button>
             </fieldset>
         </form>
-
-        <div id="chatArea" style="display: none;">
-            <fieldset>
-                <legend>聊天室</legend>
-                <textarea id="chatLog" rows="10" cols="50" readonly></textarea>
-                <br>
-                <input type="text" id="messageInput">
-                <button id="sendButton">发送</button>
-                <button id="exitButton">退出</button>
-            </fieldset>
-        </div>
     </div>
-
-    <script>
-        if (typeof window.fetch !== 'function') {
-            require('whatwg-fetch');
-        }
-        var currentRoomId = null;
-        var messageUpdateInterval;
-
-        document.getElementById('roomForm').addEventListener('submit', function (event) {
-            event.preventDefault();
-            const nickname = document.getElementById('nickname').value;
-            const roomId = document.getElementById('roomId').value;
-            fetch('/join', {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json; charset=utf-8' },
-                body: JSON.stringify({ nickname, roomId })
-            }).then(function (response) {
-                if (response.ok) {
-                    document.getElementById('roomForm').style.display = 'none';
-                    document.getElementById('chatArea').style.display = 'block';
-                    loadMessages(roomId);
-                    currentRoomId = roomId;
-                    startMessageUpdates();
-                }
-            });
-        });
-
-        document.getElementById('sendButton').addEventListener('click', function () {
-            const message = document.getElementById('messageInput').value;
-            fetch('/send', {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json; charset=utf-8' },
-                body: JSON.stringify({ message, roomId: currentRoomId })
-            }).then(loadMessages(currentRoomId));
-            document.getElementById('messageInput').value = '';
-            clearInterval(messageUpdateInterval);
-        });
-
-        document.getElementById('exitButton').addEventListener('click', function () {
-            fetch('/leave', {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json; charset=utf-8' },
-                body: JSON.stringify({ roomId: currentRoomId })
-            }).then(() => {
-                document.getElementById('chatLog').value = '';
-                document.getElementById('roomForm').style.display = 'block';
-                document.getElementById('chatArea').style.display = 'none';
-            });
-        });
-
-        function startMessageUpdates() {
-            loadMessages(currentRoomId);
-            messageUpdateInterval = setInterval(() => loadMessages(currentRoomId), 30000); // 30 秒
-        }
-
-        function loadMessages(roomId) {
-            fetch(`/messages?roomId=${roomId}`).then(response => response.json()).then(updateChatLog);
-        }
-
-        function updateChatLog(messages) {
-            const chatLog = document.getElementById('chatLog');
-            chatLog.value = messages.map(msg => `${new Date(msg.timestamp).toLocaleString()}: ${msg.nickname} - ${msg.message}`).join('\n');
-        }
-    </script>
 </body>
 
 </html>

+ 117 - 0
index.html.bak

@@ -0,0 +1,117 @@
+<!DOCTYPE html>
+<html lang="zh-Hans">
+
+<head>
+    <meta charset="UTF-8">
+    <title>聊天室</title>
+    <script>
+        // Polyfill for IE9 and below to support addEventListener
+        if (!Element.prototype.addEventListener) {
+            Element.prototype.addEventListener = function (eventName, callback) {
+                this.attachEvent('on' + eventName, callback);
+            };
+        }
+
+        // Polyfill for IE9 and below to support removeEventListener
+        if (!Element.prototype.removeEventListener) {
+            Element.prototype.removeEventListener = function (eventName, callback) {
+                this.detachEvent('on' + eventName, callback);
+            };
+        }
+    </script>
+    <link type="text/css" rel="stylesheet" href="html-chat.css">
+</head>
+
+<body>
+    <div class="container">
+        <form id="roomForm">
+            <fieldset>
+                <legend>主页</legend>
+                <label for="nickname">昵称:</label>
+                <input type="text" id="nickname" name="nickname" value="匿名">
+                <br>
+                <label for="roomId">房间号:</label>
+                <input type="text" id="roomId" name="roomId">
+                <br>
+                <button type="submit">进入聊天室</button>
+            </fieldset>
+        </form>
+
+        <div id="chatArea" style="display: none;">
+            <fieldset>
+                <legend>聊天室</legend>
+                <textarea id="chatLog" rows="10" cols="50" readonly></textarea>
+                <br>
+                <input type="text" id="messageInput">
+                <button id="sendButton">发送</button>
+                <button id="exitButton">退出</button>
+            </fieldset>
+        </div>
+    </div>
+
+    <script>
+        if (typeof window.fetch !== 'function') {
+            require('whatwg-fetch');
+        }
+        var currentRoomId = null;
+        var messageUpdateInterval;
+
+        document.getElementById('roomForm').addEventListener('submit', function (event) {
+            event.preventDefault();
+            const nickname = document.getElementById('nickname').value;
+            const roomId = document.getElementById('roomId').value;
+            fetch('/join', {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json; charset=utf-8' },
+                body: JSON.stringify({ nickname, roomId })
+            }).then(function (response) {
+                if (response.ok) {
+                    document.getElementById('roomForm').style.display = 'none';
+                    document.getElementById('chatArea').style.display = 'block';
+                    loadMessages(roomId);
+                    currentRoomId = roomId;
+                    startMessageUpdates();
+                }
+            });
+        });
+
+        document.getElementById('sendButton').addEventListener('click', function () {
+            const message = document.getElementById('messageInput').value;
+            fetch('/send', {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json; charset=utf-8' },
+                body: JSON.stringify({ message, roomId: currentRoomId })
+            }).then(loadMessages(currentRoomId));
+            document.getElementById('messageInput').value = '';
+            clearInterval(messageUpdateInterval);
+        });
+
+        document.getElementById('exitButton').addEventListener('click', function () {
+            fetch('/leave', {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json; charset=utf-8' },
+                body: JSON.stringify({ roomId: currentRoomId })
+            }).then(() => {
+                document.getElementById('chatLog').value = '';
+                document.getElementById('roomForm').style.display = 'block';
+                document.getElementById('chatArea').style.display = 'none';
+            });
+        });
+
+        function startMessageUpdates() {
+            loadMessages(currentRoomId);
+            messageUpdateInterval = setInterval(() => loadMessages(currentRoomId), 30000); // 30 秒
+        }
+
+        function loadMessages(roomId) {
+            fetch(`/messages?roomId=${roomId}`).then(response => response.json()).then(updateChatLog);
+        }
+
+        function updateChatLog(messages) {
+            const chatLog = document.getElementById('chatLog');
+            chatLog.value = messages.map(msg => `${new Date(msg.timestamp).toLocaleString()}: ${msg.nickname} - ${msg.message}`).join('\n');
+        }
+    </script>
+</body>
+
+</html>

+ 0 - 91
new_chat.html

@@ -1,91 +0,0 @@
-<!DOCTYPE html>
-<html lang="zh-Hans">
-
-<head>
-    <meta charset="UTF-8">
-    <title>聊天室 - {{ roomid }}</title>
-    <style>
-        body {
-            font-family: Arial, sans-serif;
-            background-color: #f4f4f4;
-            margin: 0;
-            padding: 0;
-            color: #333;
-        }
-
-        .container {
-            width: 80%;
-            max-width: 600px;
-            margin: 20px auto;
-            padding: 20px;
-            background-color: #fff;
-            border: 1px solid #ccc;
-            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
-            border-radius: 5px;
-            /* IE9+ */
-        }
-
-        fieldset {
-            border: 1px solid #ddd;
-            padding: 10px;
-            margin-bottom: 5px;
-        }
-
-        legend {
-            font-weight: bold;
-            padding: 0 10px;
-        }
-
-        label {
-            display: block;
-            margin-bottom: 5px;
-        }
-
-        input[type="text"],
-        textarea {
-            box-sizing: border-box;
-            max-width: 100%;
-            width: 100%;
-            padding: 8px;
-            margin-bottom: 10px;
-            border: 1px solid #ddd;
-            border-radius: 3px;
-            /* IE9+ */
-        }
-
-        button {
-            padding: 8px 15px;
-            background-color: #007BFF;
-            color: #fff;
-            border: none;
-            border-radius: 3px;
-            /* IE9+ */
-            cursor: pointer;
-        }
-
-        button:hover {
-            background-color: #0056b3;
-        }
-    </style>
-    <meta http-equiv="refresh" content="60">
-</head>
-
-<body>
-    <div class="container">
-        <form action="/send_message" method="post">
-            <fieldset>
-                <legend>聊天室 - {{ roomid }}</legend>
-                <textarea id="chatLog" rows="10" cols="50" readonly></textarea>
-                <br>
-                <label for="messageInput">消息:</label>
-                <input type="text" id="messageInput" name="messageInput">
-                <button type="submit">发送</button>
-                <a href="."><button type="button">退出</button></a>
-            </fieldset>
-            <input type="text" id="nickname" name="nickname" value="{{ nickname }}" style="display: none;">
-            <input type="text" id="roomid" name="roomid" value="{{ roomid }}" style="display: none;">
-        </form>
-    </div>
-</body>
-
-</html>

+ 0 - 89
new_index.html

@@ -1,89 +0,0 @@
-<!DOCTYPE html>
-<html lang="zh-Hans">
-
-<head>
-    <meta charset="UTF-8">
-    <title>聊天室</title>
-    <style>
-        body {
-            font-family: Arial, sans-serif;
-            background-color: #f4f4f4;
-            margin: 0;
-            padding: 0;
-            color: #333;
-        }
-
-        .container {
-            width: 80%;
-            max-width: 600px;
-            margin: 20px auto;
-            padding: 20px;
-            background-color: #fff;
-            border: 1px solid #ccc;
-            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
-            border-radius: 5px;
-            /* IE9+ */
-        }
-
-        fieldset {
-            border: 1px solid #ddd;
-            padding: 10px;
-            margin-bottom: 5px;
-        }
-
-        legend {
-            font-weight: bold;
-            padding: 0 10px;
-        }
-
-        label {
-            display: block;
-            margin-bottom: 5px;
-        }
-
-        input[type="text"],
-        textarea {
-            box-sizing: border-box;
-            max-width: 100%;
-            width: 100%;
-            padding: 8px;
-            margin-bottom: 10px;
-            border: 1px solid #ddd;
-            border-radius: 3px;
-            /* IE9+ */
-        }
-
-        button {
-            padding: 8px 15px;
-            background-color: #007BFF;
-            color: #fff;
-            border: none;
-            border-radius: 3px;
-            /* IE9+ */
-            cursor: pointer;
-        }
-
-        button:hover {
-            background-color: #0056b3;
-        }
-    </style>
-</head>
-
-<body>
-    <div class="container">
-        <form action="/chat" method="get">
-            <fieldset>
-                <legend>主页</legend>
-                <label for="nickname">昵称</label>
-                <input type="text" id="nickname" name="nickname" value="匿名">
-                <br>
-                <label for="roomid">房间号:</label>
-                <input type="text" id="roomid" name="roomid" value="默认">
-                <br>
-                <button type="submit">进入聊天室</button>
-            </fieldset>
-        </form>
-    </div>
-</body>
-
-</html>

+ 168 - 108
server.py

@@ -1,128 +1,188 @@
+#!/usr/bin/env python3
+import http.server
+import socketserver
+import configparser
 import os
-import json
-import datetime
-from configparser import ConfigParser
-from http.server import BaseHTTPRequestHandler, HTTPServer
-import ssl
+import time
+from urllib.parse import parse_qs
 import argparse
+import logging
 
-# 使用ConfigParser来读写.ini文件
-config = ConfigParser()
+# Configure logging
+logging.basicConfig(level=logging.INFO)
 
-class ChatServer(BaseHTTPRequestHandler):
+class ChatConfig:
+    def __init__(self):
+        self.config = configparser.ConfigParser()
+        self.config_file = 'chat_records.ini'
+        if not os.path.exists(self.config_file):
+            open(self.config_file, 'w').close()  # Create an empty file if it doesn't exist
+        self.config.read(self.config_file)
+
+class ChatServer(http.server.BaseHTTPRequestHandler):
     rooms = {}
     max_rooms = 32
     max_messages_per_room = 50
     max_message_length = 2048
     max_messages_per_minute = 20
+    message_rate_limit = {}  # To track messages per minute
 
-    @classmethod
-    def load_rooms(cls):
-        """从.ini文件加载聊天室数据"""
-        config.read('chat_records.ini')
-        for section in config.sections():
-            cls.rooms[section] = {
-                'users': json.loads(config.get(section, 'users')),
-                'messages': json.loads(config.get(section, 'messages'))
-            }
-
-    @classmethod
-    def save_rooms(cls):
-        """将聊天室数据保存到.ini文件"""
-        config.clear()  # 清除旧的数据
-        for room_id, room in cls.rooms.items():
-            config.add_section(room_id)
-            config.set(room_id, 'users', json.dumps(room['users']))
-            config.set(room_id, 'messages', json.dumps(room['messages']))
-        with open('chat_records.ini', 'w', encoding='utf-8') as configfile:
-            config.write(configfile)
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.load_rooms()
+
+    def do_GET(self):
+        try:
+            if self.path == '/':
+                self.send_response(302)
+                self.send_header('Location', '/index.html')
+                self.end_headers()
+            elif self.path == '/index.html':
+                self.send_file('index.html')
+            elif self.path == '/send_message':
+                self.send_response(302)
+                self.send_header('Location', '/chat')
+                self.end_headers()
+            elif self.path.startswith('/chat'):
+                query_params = parse_qs(self.path[6:])
+                nickname = query_params.get('nickname', ['匿名'])[0]
+                roomid = query_params.get('roomid', ['默认'])[0]
+                self.send_response(200)
+                self.send_header('Content-type', 'text/html')
+                self.end_headers()
+                self.wfile.write(self.generate_chat_html(nickname, roomid).encode('utf-8'))
+            elif self.path.endswith('.css'):
+                self.send_file(self.path.lstrip('/'))
+            else:
+                self.send_error(404)
+        except Exception as e:
+            logging.error(f"Error processing GET request: {e}")
+            self.send_error(500)
 
     def do_POST(self):
-        content_length = int(self.headers['Content-Length'])
-        post_data = self.rfile.read(content_length)
-        data = json.loads(post_data)
-
-        if self.path == '/join':
-            self.join(data['nickname'], data['roomId'])
-        elif self.path == '/send':
-            self.send(data['message'], data['roomId'])
-        elif self.path == '/leave':
-            self.leave(data['roomId'])
-        
-        self.save_rooms()
+        try:
+            if self.path == '/send_message':
+                content_length = int(self.headers['Content-Length'])
+                post_data = self.rfile.read(content_length).decode('utf-8')
+                post_data = parse_qs(post_data)
+                nickname = post_data.get('nickname', ['匿名'])[0]
+                roomid = post_data.get('roomid', ['默认'])[0]
+                message = post_data.get('messageInput', [''])[0]
 
-    def do_GET(self):
-        if self.path == '/':
-            self.send_response(200)
-            self.send_header('Content-type', 'text/html')
-            self.end_headers()
-            with open('index.html', 'rb') as file:
-                self.wfile.write(file.read())
-        elif self.path.startswith('/messages'):
-            self.messages(self.path.split('=')[1])
-        self.save_rooms()
-
-    def join(self, nickname, room_id):
-        if not room_id:
-            room_id = 'default'
-        if room_id not in self.rooms:
-            self.rooms[room_id] = {'users': [], 'messages': []}
-            if len(self.rooms) > self.max_rooms:
+                # Rate limiting
+                if self.check_message_rate_limit(roomid):
+                    if message and len(message) <= self.max_message_length:
+                        self.add_message(roomid, nickname, message)
+                    self.send_response(302)
+                    self.send_header('Location', f'/chat?nickname={nickname}&roomid={roomid}')
+                    self.end_headers()
+                else:
+                    self.send_error(429, "Too Many Requests")
+            else:
+                self.send_error(404)
+        except Exception as e:
+            logging.error(f"Error processing POST request: {e}")
+            self.send_error(500)
+
+    def check_message_rate_limit(self, roomid):
+        current_time = time.time()
+        if roomid not in self.message_rate_limit:
+            self.message_rate_limit[roomid] = [current_time]
+            return True
+
+        # Remove old timestamps
+        self.message_rate_limit[roomid] = [t for t in self.message_rate_limit[roomid] if t > current_time - 60]
+
+        # Check if we have exceeded the limit
+        if len(self.message_rate_limit[roomid]) >= self.max_messages_per_minute:
+            return False
+
+        self.message_rate_limit[roomid].append(current_time)
+        return True
+
+    def add_message(self, roomid, nickname, message):
+        if roomid not in self.rooms:
+            if len(self.rooms) >= self.max_rooms:
                 oldest_room = next(iter(self.rooms))
                 del self.rooms[oldest_room]
-        self.rooms[room_id]['users'].append(nickname)
-        self.send_response(200)
-        self.end_headers()
-
-    def send(self, message, room_id):
-        if not room_id:
-            room_id = 'default'
-        nickname = "匿名"  # 默认昵称,应根据实际情况获取
-        if room_id in self.rooms and self.rooms[room_id]['users']:
-            nickname = self.rooms[room_id]['users'][-1]  # 获取最新加入用户的昵称
-        if len(message) > self.max_message_length:
-            return
-        if len(self.rooms[room_id]['messages']) >= self.max_messages_per_room:
-            self.rooms[room_id]['messages'].pop(0)
-        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-        self.rooms[room_id]['messages'].append({"timestamp": timestamp, "nickname": nickname, "message": message})
-        self.send_response(200)
-        self.end_headers()
-
-    def leave(self, room_id):
-        self.send_response(200)
-        self.end_headers()
-
-    def messages(self, room_id):
-        if not room_id:
-            room_id = 'default'
-        self.send_response(200)
-        self.send_header('Content-type', 'application/json')
-        self.end_headers()
-        self.wfile.write(json.dumps(self.rooms[room_id]['messages']).encode())
+            self.rooms[roomid] = []
+        messages = self.rooms[roomid]
+        timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
+        messages.append(f'{timestamp} {nickname}: {message}')
+        if len(messages) > self.max_messages_per_room:
+            messages.pop(0)
 
-if __name__ == '__main__':
+    def save_rooms(self):
+        config = ChatConfig().config
+        for roomid, messages in self.rooms.items():
+            config[roomid] = {'messages': '\n'.join(messages)}
+        with open(ChatConfig().config_file, 'w') as configfile:
+            config.write(configfile, encoding='utf-8')
+
+    def load_rooms(self):
+        config = ChatConfig().config
+        for section in config.sections():
+            self.rooms[section] = config.get(section, 'messages').split('\n')
+
+    def generate_chat_html(self, nickname, roomid):
+        chat_log = '<br>'.join(self.rooms.get(roomid, []))
+        return f'''
+<!DOCTYPE html>
+<html lang="zh-Hans">
+<head>
+    <meta charset="UTF-8">
+    <title>聊天室 - {roomid}</title>
+    <meta http-equiv="refresh" content="60">
+    <link type="text/css" rel="stylesheet" href="html-chat.css">
+</head>
+<body>
+    <div class="container">
+        <form action="/send_message" method="post">
+            <fieldset>
+                <legend>聊天室 - {roomid}</legend>
+                <textarea id="chatLog" rows="10" cols="50" readonly>{chat_log}</textarea>
+                <br>
+                <label for="messageInput">{nickname}说:</label>
+                <input type="text" id="messageInput" name="messageInput">
+                <button type="submit">发送</button>
+                <a href="."><button type="button">退出</button></a>
+            </fieldset>
+            <input type="text" id="nickname" name="nickname" value="{nickname}" style="display: none;">
+            <input type="text" id="roomid" name="roomid" value="{roomid}" style="display: none;">
+        </form>
+    </div>
+</body>
+</html>
+'''
+
+    def send_file(self, filename):
+        try:
+            if filename.endswith('.css'):
+                self.send_response(200)
+                self.send_header('Content-type', 'text/css')
+            else:
+                self.send_response(200)
+                self.send_header('Content-type', 'text/html; charset=UTF-8')
+
+            self.end_headers()
+            with open(filename, 'rb') as file:
+                self.wfile.write(file.read())
+        except FileNotFoundError:
+            logging.error(f"File not found: {filename}")
+            self.send_error(404)
+
+
+def main():
     parser = argparse.ArgumentParser(description='Simple chat server.')
-    parser.add_argument('--port', type=int, default=2666, help='Port to listen on')
+    parser.add_argument('--port', type=int, default=8000, help='Port to listen on.')
     args = parser.parse_args()
 
     server_address = ('0.0.0.0', args.port)
-    httpd = HTTPServer(server_address, ChatServer)
-    
-    # 检查证书和私钥文件是否存在
-    if os.path.exists("server.crt") and os.path.exists("server.key"):
-        # 创建SSL上下文并加载证书和私钥
-        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
-        try:
-            context.load_cert_chain(certfile="server.crt", keyfile="server.key")
-            # 将SSL上下文应用于HTTP服务器
-            httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
-            print(f'Starting HTTPS server on port {args.port}')
-        except ssl.SSLError as e:
-            print(f'Error loading SSL certificate or key: {e}')
-            print(f'Continuing with HTTP server on port {args.port}')
-    else:
-        print(f'Certificate or key files not found. Continuing with HTTP service on port {args.port}')
-
-    ChatServer.load_rooms()
-    httpd.serve_forever()
+    httpd = socketserver.TCPServer(server_address, ChatServer)
+    httpd.allow_reuse_address = True
+
+    print(f'Starting server on port {args.port}...')
+    httpd.serve_forever()
+
+if __name__ == '__main__':
+    main()

+ 2 - 1
需求.md

@@ -56,6 +56,7 @@
 <head>
     <meta charset="UTF-8">
     <title>聊天室 - {{ roomid }}</title>
+    <link type="text/css" rel="stylesheet" href="html-chat.css">
     <meta http-equiv="refresh" content="60">
 </head>
 
@@ -66,7 +67,7 @@
                 <legend>聊天室 - {{ roomid }}</legend>
                 <textarea id="chatLog" rows="10" cols="50" readonly></textarea>
                 <br>
-                <label for="messageInput">消息:</label>
+                <label for="messageInput">{{ nickname }}说:</label>
                 <input type="text" id="messageInput" name="messageInput">
                 <button type="submit">发送</button>
                 <a href="."><button type="button">退出</button></a>