test.html 1004 B

1234567891011121314151617181920212223242526272829
  1. <!DOCTYPE html>
  2. <html lang="zh-cn">
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title>test</title>
  6. </head>
  7. <body>
  8. <textarea id="chat-log" cols="100" rows="20"></textarea><br>
  9. <input id="chat-message-input" type="text" size="100"><br>
  10. <input id="chat-message-submit" type="button" value="Send">
  11. {{ room_name|json_script:"room-name" }}
  12. <script>
  13. // 根据roomName拼接websocket请求地址,建立长连接
  14. // 请求url地址为/ws/chat/<room_name>/
  15. const username = "test"
  16. const wss_protocol = (window.location.protocol == 'https:') ? 'wss://' : 'ws://';
  17. const chatSocket = new WebSocket(
  18. wss_protocol + window.location.host + '/ws/' + username + '/'
  19. );
  20. // 从后台接收到数据时触发此方法
  21. // 接收到后台数据后对其解析,并加入到聊天记录chat-log
  22. chatSocket.onmessage = function (e) {
  23. const data = JSON.parse(e.data);
  24. document.querySelector('#chat-log').value += (data.message + '\n');
  25. };
  26. </script>
  27. </body>
  28. </html>