Pārlūkot izejas kodu

【优化】数据结构

PJ-568 2 gadi atpakaļ
vecāks
revīzija
31ef202dd0
2 mainītis faili ar 63 papildinājumiem un 12 dzēšanām
  1. 24 8
      index.html
  2. 39 4
      server.py

+ 24 - 8
index.html

@@ -36,7 +36,8 @@
             background-color: #fff;
             border: 1px solid #ccc;
             box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
-            border-radius: 5px; /* IE9+ */
+            border-radius: 5px;
+            /* IE9+ */
         }
 
         fieldset {
@@ -63,7 +64,8 @@
             padding: 8px;
             margin-bottom: 10px;
             border: 1px solid #ddd;
-            border-radius: 3px; /* IE9+ */
+            border-radius: 3px;
+            /* IE9+ */
         }
 
         button {
@@ -71,7 +73,8 @@
             background-color: #007BFF;
             color: #fff;
             border: none;
-            border-radius: 3px; /* IE9+ */
+            border-radius: 3px;
+            /* IE9+ */
             cursor: pointer;
         }
 
@@ -109,7 +112,11 @@
     </div>
 
     <script>
-        let currentRoomId = null;
+        if (typeof window.fetch !== 'function') {
+            require('whatwg-fetch');
+        }
+        var currentRoomId = null;
+        var messageUpdateInterval;
 
         document.getElementById('roomForm').addEventListener('submit', function (event) {
             event.preventDefault();
@@ -117,14 +124,15 @@
             const roomId = document.getElementById('roomId').value;
             fetch('/join', {
                 method: 'POST',
-                headers: { 'Content-Type': 'application/json' },
+                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                 body: JSON.stringify({ nickname, roomId })
-            }).then(response => {
+            }).then(function (response) {
                 if (response.ok) {
                     document.getElementById('roomForm').style.display = 'none';
                     document.getElementById('chatArea').style.display = 'block';
                     loadMessages(roomId);
                     currentRoomId = roomId;
+                    startMessageUpdates();
                 }
             });
         });
@@ -133,22 +141,30 @@
             const message = document.getElementById('messageInput').value;
             fetch('/send', {
                 method: 'POST',
-                headers: { 'Content-Type': 'application/json' },
+                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' },
+                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);
         }

+ 39 - 4
server.py

@@ -1,9 +1,13 @@
 import os
+import json
+import datetime
+from configparser import ConfigParser
 from http.server import BaseHTTPRequestHandler, HTTPServer
 import ssl
-import json
 import argparse
-import datetime
+
+# 使用ConfigParser来读写.ini文件
+config = ConfigParser()
 
 class ChatServer(BaseHTTPRequestHandler):
     rooms = {}
@@ -12,6 +16,27 @@ class ChatServer(BaseHTTPRequestHandler):
     max_message_length = 2048
     max_messages_per_minute = 20
 
+    @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 do_POST(self):
         content_length = int(self.headers['Content-Length'])
         post_data = self.rfile.read(content_length)
@@ -23,6 +48,8 @@ class ChatServer(BaseHTTPRequestHandler):
             self.send(data['message'], data['roomId'])
         elif self.path == '/leave':
             self.leave(data['roomId'])
+        
+        self.save_rooms()
 
     def do_GET(self):
         if self.path == '/':
@@ -33,8 +60,11 @@ class ChatServer(BaseHTTPRequestHandler):
                 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:
@@ -45,6 +75,8 @@ class ChatServer(BaseHTTPRequestHandler):
         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]  # 获取最新加入用户的昵称
@@ -62,6 +94,8 @@ class ChatServer(BaseHTTPRequestHandler):
         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()
@@ -69,10 +103,10 @@ class ChatServer(BaseHTTPRequestHandler):
 
 if __name__ == '__main__':
     parser = argparse.ArgumentParser(description='Simple chat server.')
-    parser.add_argument('--port', type=int, default=8000, help='Port to listen on')
+    parser.add_argument('--port', type=int, default=2666, help='Port to listen on')
     args = parser.parse_args()
 
-    server_address = ('', args.port)
+    server_address = ('0.0.0.0', args.port)
     httpd = HTTPServer(server_address, ChatServer)
     
     # 检查证书和私钥文件是否存在
@@ -90,4 +124,5 @@ if __name__ == '__main__':
     else:
         print(f'Certificate or key files not found. Continuing with HTTP service on port {args.port}')
 
+    ChatServer.load_rooms()
     httpd.serve_forever()