DJango 서버개발, Django Channels를 이용한 실시간 기능 구현하기


<h2>Chat Room</h2>
<div id=”chat-log”></div>
<input type=”text” id=”username” placeholder=”Enter your name” />
<input type=”text” id=”message” placeholder=”Message” />
<button id=”send”>Send</button>

<script>
$(document).ready(function(){
const roomName = “{{ room_name }}”;
const chatSocket = new WebSocket(
‘ws://’ + window.location.host + ‘/ws/chat/’ + roomName + ‘/’
);

chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
$(‘#chat-log’).append(data.username + “: ” + data.message + “<br>”);
};

$(‘#send’).click(function(){
const messageInputDom = $(‘#message’);
const message = messageInputDom.val();
const username = $(‘#username’).val();
chatSocket.send(JSON.stringify({
‘message’: message,
‘username’: username
}));
messageInputDom.val(”);
});
});
</script>