django_websocket实现简单聊天室
一、安装模块
pip install channels
pip install channels-redis
二、代码
#websocket_v1/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "app01.apps.App01Config", "channels" ] ASGI_APPLICATION="websocket_v1.routing.application" CHANNEL_LAYERS={ "default":{ "BACKEND":"channels_redis.core.RedisChannelLayer", "CONFIG":{ "hosts":["redis://:123456@127.0.0.1:6379/0"] } } }
#websocket_v1/urls.py from django.contrib import admin from django.conf.urls import include, url from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index), url(r'^chat/', include('app01.urls')), ]
#websocket_v1/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter from app01 import routing application=ProtocolTypeRouter({ "websocket":AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), })
#app01/urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^(?P<room_name>[^/]+)/$', views.room, name='room'), ]
#app01/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns=[ re_path(r'^ws/chat/(?P<room_name>[^/]+)/$',consumers.Chatting), ]
#app01/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class Chatting(AsyncWebsocketConsumer): async def connect(self): print(self.scope) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json["message"] print(message) await self.channel_layer.group_send( self.room_group_name, { "type":"chat_message", "message":message } ) async def chat_message(self,event): message="匿名聊天:"+event["message"] print("返回") await self.send(text_data=json.dumps( {"message":message} ))
#app01/views.py from django.shortcuts import render from django.utils.safestring import mark_safe import json def index(request): return render(request, 'chat/index.html', {}) def room(request, room_name): return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)) })
#index.html <!-- chat/templates/chat/index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Rooms</title> </head> <body> What chat room would you like to enter?<br/> <input id="room-name-input" type="text" size="100"/><br/> <input id="room-name-submit" type="button" value="Enter"/> <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; window.location.pathname = '/chat/' + roomName + '/'; }; </script> </body> </html>
#chat.html <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</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"/> </body> <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> </html>