<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8"/>
    <title>test</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}

<script>
    // 根据roomName拼接websocket请求地址，建立长连接
    //  请求url地址为/ws/chat/<room_name>/
    const username = "test"
    const wss_protocol = (window.location.protocol == 'https:') ? 'wss://' : 'ws://';
    const chatSocket = new WebSocket(
        wss_protocol + window.location.host + '/ws/' + username + '/'
    );
    // 从后台接收到数据时触发此方法
    // 接收到后台数据后对其解析，并加入到聊天记录chat-log
    chatSocket.onmessage = function (e) {
        const data = JSON.parse(e.data);
        document.querySelector('#chat-log').value += (data.message + '\n');
    };
</script>
</body>
</html>