websocket
- 网易聊天室"htmlcode">
<body> <!-- 输入内容--> <input type="text" id="input"> <!-- 提交数据--> <button> 提交数据</button> <!-- 显示内容--> <div> <div ></div> </div> <script> var input=document.getElementById('input'); var button=document.querySelector('button'); var message=document.querySelector('div'); //websocket在浏览器端如何使用 //现在html已经提供了websocket,我们可以直接使用 var socket= new WebSocket('ws://echo.websocket.org'); socket.onopen=function () { message.innerHTML='连接成功了' }; //socket.addEventListener('open',function (data) { // message.innerHTML='连接成功了' //}); //点击事件 button.onclick=function () { request=input.value; socket.send(request) } //获取返回数据 socket.onmessage=function (data) { message.innerHTML=data.data }; socket.onclose=function (data) { message.innerHTML=data.data } </script> </body>
优化前端代码
button.onclick=function () { request=input.value; socket.send(request); input.value='' } //获取返回数据 socket.onmessage = function (data) { var dv=document.createElement('div'); dv.innerHTML=data.data; message.appendChild(dv) };
websocket 事件
事件 事件处理函数 描述 open socket.onopen 连接建立是触发 message socket.onmessage 客户端收到服务端数据是触发 error socket.error 通信发生错误时触发 close socket.close 连接关闭时触发websocket方法
方法 描述 socket.send() 使用连接发送数据 socket.close() 关闭连接websocke treadyState值的状态
值 描述 0 (CONNECTING) 正在链接中 1 (OPEN) 已经链接并且可以通讯 2 (CLOSING) 连接正在关闭 3 (CLOSED) 连接已关闭或者没有链接成功自建websocket服务端
准备前端页面
<!-- 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"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 = '/web/' + roomName + '/'; }; </script> </body> </html>
编辑django的views,使其返回数据
# chat/views.py from django.shortcuts import render def index(request): return render(request, 'chat/index.html', {})
修改url
from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$', index, name='index'), ]
跟settings同级目录下创建routing.py 文件
# mysite/routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # (http->django views is added by default) })
编辑settings文件,将channels添加到installed_apps里面
INSTALLED_APPS = [ 'channels', 'chat', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
并添加channel的配置信息
ASGI_APPLICATION = 'mysite.routing.application'
准备聊天室的页面
<!-- 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|safe }}; 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>
准备views文件,使其返回页面
def room(request, room_name): return render(request, 'chat/room.html', { 'room_name_json':json.dumps(room_name) })
修改url
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^("htmlcode">
from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message }))
创建ws的路由
# chat/routing.py from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/chat/("htmlcode">
# mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), })
执行数据库的迁移命令
python manage.py migrate
要实现群聊功能,还需要准备redis
docker run -p 6379:6379 -d redis:2.8 pip3 install channels_redis
将redis添加到settings的配置文件中
# mysite/settings.py # Channels ASGI_APPLICATION = 'mysite.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, }
修改consumer.py文件
from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message }))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
圆月山庄资源网 Design By www.vgjia.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]