Global Chat

This commit is contained in:
Xamora 2023-11-27 15:10:06 +01:00
parent 56b6f0e138
commit c16d281892
7 changed files with 78 additions and 30 deletions

36
frontend/consumers.py Normal file
View File

@ -0,0 +1,36 @@
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'message':message
}
)
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dumps({
'type':'chat',
'message':message
}))

6
frontend/routing.py Normal file
View File

@ -0,0 +1,6 @@
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi())
]

View File

@ -1,37 +1,9 @@
body {
--nav-width: 200px;
margin: 0 0 0 var(--nav-width);
margin: 10;
font-family: 'Quicksand', sans-serif;
font-size: 18px;
}
.nav {
position: fixed;
top: 0;
left: 0;
width: var(--nav-width);
height: 100vh;
background: #222222;
}
.nav__link {
display: block;
padding: 12px 18px;
text-decoration: none;
color: #eeeeee;
font-weight: 500;
}
.nav__link:hover {
background: rgba(255, 255, 255, 0.05);
}
#app {
margin: 2em;
line-height: 1.5;
font-weight: 500;
}
a {
color: #009579;
}

View File

@ -11,6 +11,14 @@ export default class extends AbstractView {
this.chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
console.log('Data:', data)
if (data.type === 'chat') {
let messages = document.getElementById('messages')
messages.insertAdjacentHTML('beforeend', `
<div><p>${data.message}</p></div>
`)
}
}
}

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Chat</title>
</head>
<body>
<h1>Chat</h1>
<form id="form">
<input type="text" name="message" />
</form>
<script type="text/javascript">
let url = `ws://${window.location.host}/ws/socket-server/`
const chatSocket = new WebSocket(url)
chatSocket.onmessage = function(e){
let data = JSON.parse(e.data)
console.log('Data:', data)
}
</script>
</b

View File

@ -12,6 +12,7 @@
<a href="/" class="nav__link" data-link>Dashboard</a>
<a href="/posts" class="nav__link" data-link>Posts</a>
<a href="/settings" class="nav__link" data-link>Settings</a>
<a href="/chat" class="nav__link" data-link>Chat</a>
</nav>
<div id="app"></div>
<script type="module" src="{% static 'js/index.js' %}"></script>

View File

@ -2,5 +2,6 @@ from django.shortcuts import render
# Create your views here.
def index_view(req):
return render(req, 'index.html');