Ver Fonte

【修复】写入字符串格式

PJ-568 há 2 anos atrás
pai
commit
e1e8dc09f1
2 ficheiros alterados com 12 adições e 127 exclusões
  1. 0 117
      index.html.bak
  2. 12 10
      server.py

+ 0 - 117
index.html.bak

@@ -1,117 +0,0 @@
-<!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>

+ 12 - 10
server.py

@@ -16,8 +16,9 @@ class ChatConfig:
         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)
+            open(self.config_file, 'w', encoding='utf-8').close()
+        with open(self.config_file, 'r', encoding='utf-8') as config_file:
+            self.config.read_file(config_file)
 
 class ChatServer(http.server.BaseHTTPRequestHandler):
     rooms = {}
@@ -41,7 +42,7 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
                 self.send_file('index.html')
             elif self.path == '/send_message':
                 self.send_response(302)
-                self.send_header('Location', '/chat')
+                self.send_header('Location', f'/chat?nickname={nickname}&roomid={roomid}')
                 self.end_headers()
             elif self.path.startswith('/chat'):
                 query_params = parse_qs(self.path[6:])
@@ -50,7 +51,7 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
                 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'))
+                self.wfile.write(self.generate_chat_html(nickname, roomid))
             elif self.path.endswith('.css'):
                 self.send_file(self.path.lstrip('/'))
             else:
@@ -74,8 +75,9 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
                     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.send_header('Location', f'/chat?nickname={nickname.encode('utf-8').decode('latin1')}&roomid={roomid.encode('utf-8').decode('latin1')}')
                     self.end_headers()
+                    self.save_rooms()
                 else:
                     self.send_error(429, "Too Many Requests")
             else:
@@ -116,8 +118,8 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
         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')
+        with open(ChatConfig().config_file, 'w', encoding='utf-8') as configfile:
+            config.write(configfile)
 
     def load_rooms(self):
         config = ChatConfig().config
@@ -125,7 +127,7 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
             self.rooms[section] = config.get(section, 'messages').split('\n')
 
     def generate_chat_html(self, nickname, roomid):
-        chat_log = '<br>'.join(self.rooms.get(roomid, []))
+        chat_log = '\n'.join(self.rooms.get(roomid, []))
         return f'''
 <!DOCTYPE html>
 <html lang="zh-Hans">
@@ -153,13 +155,13 @@ class ChatServer(http.server.BaseHTTPRequestHandler):
     </div>
 </body>
 </html>
-'''
+'''.encode('utf-8')
 
     def send_file(self, filename):
         try:
             if filename.endswith('.css'):
                 self.send_response(200)
-                self.send_header('Content-type', 'text/css')
+                self.send_header('Content-type', 'text/css; charset=UTF-8')
             else:
                 self.send_response(200)
                 self.send_header('Content-type', 'text/html; charset=UTF-8')