基于django channel实现websocket的聊天室的方法示例
websocket
- 网易聊天室?
- web微信?
- 直播?
假如你工作以后,你的老板让你来开发一个内部的微信程序,你需要怎么办?我们先来分析一下里面的技术难点
- 消息的实时性?
- 实现群聊
现在有这样一个需求,老板给到你了,关乎你是否能转正?你要怎么做?
我们先说消息的实时性,按照我们目前的想法是我需要用http协议来做,那么http协议怎么来做那?
是不是要一直去访问我们的服务器,问服务器有没有人给我发消息,有没有人给我发消息?那么大家认为我多长时间去访问一次服务比较合适那?1分钟1次?1分钟60次?那这样是不是有点问题那?咱们都知道http发起一次请求就需要三次握手,四次断开,那么这样是不是对我服务器资源是严重的浪费啊?对我本地的资源是不是也是严重的浪费啊?这种方式咱们是不是一直去服务器问啊?问有没有我的信息?有我就显示?这种方式咱们一般称为轮询
http协议:
一次请求一次相应断开
无状态的-你曾经来过sessionorcookie
在断开的情况下如果有数据只能等下次再访问的时候返回
那么我们先来总结一下,轮询优缺点
轮询02年之前使用的都是这种技术
每分钟访问60次服务器
优点:消息就基本实时
缺点:双资源浪费
长轮询2000-现在一直在使用
客户端发送一个请求-服务器接受请求-不返回-阻塞等待客户端-如果有消息了-返回给客户端
然后客户端立即请求服务器
优点:节省了部分资源,数据实时性略差
缺点:断开连接次数过多
那有没有一种方法是:我的服务器知道我的客户端在哪?有客户端的消息的时候我就把数据发给客户端
websocket是一种基于tcp的新网络协议,它实现了浏览器和服务器之间的双全工通信,允许服务端直接向客户端发送数据
websocket是一个长连接
现在咱们的前端已经支持websocket协议了,可以直接使用websocket
简单应用
优化前端代码
button.onclick=function(){ request=input.value; socket.send(request); input.value='' } //获取返回数据 socket.onmessage=function(data){ vardv=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() | 关闭连接 |
websocketreadyState值的状态
值 | 描述 |
---|---|
0(CONNECTING) | 正在链接中 |
1(OPEN) | 已经链接并且可以通讯 |
2(CLOSING) | 连接正在关闭 |
3(CLOSED) | 连接已关闭或者没有链接成功 |
自建websocket服务端
准备前端页面
ChatRooms Whatchatroomwouldyouliketoenter?
编辑django的views,使其返回数据
#chat/views.py fromdjango.shortcutsimportrender defindex(request): returnrender(request,'chat/index.html',{})
修改url
fromdjango.conf.urlsimporturl from.viewsimport* urlpatterns=[ url(r'^$',index,name='index'), ]
跟settings同级目录下创建routing.py文件
#mysite/routing.py fromchannels.routingimportProtocolTypeRouter application=ProtocolTypeRouter({ #(http->djangoviewsisaddedbydefault) })
编辑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'
准备聊天室的页面
ChatRoom
准备views文件,使其返回页面
defroom(request,room_name): returnrender(request,'chat/room.html',{ 'room_name_json':json.dumps(room_name) })
修改url
fromdjango.conf.urlsimporturl from.importviews urlpatterns=[ url(r'^$',views.index,name='index'), url(r'^(?P[^/]+)/$',views.room,name='room'), ]
实现简单的发送返回
fromchannels.generic.websocketimportWebsocketConsumer importjson classChatConsumer(WebsocketConsumer): defconnect(self): self.accept() defdisconnect(self,close_code): pass defreceive(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 fromdjango.conf.urlsimporturl from.importconsumers websocket_urlpatterns=[ url(r'^ws/chat/(?P[^/]+)/$',consumers.ChatConsumer), ]
修改application的信息
#mysite/routing.py fromchannels.authimportAuthMiddlewareStack fromchannels.routingimportProtocolTypeRouter,URLRouter importchat.routing application=ProtocolTypeRouter({ #(http->djangoviewsisaddedbydefault) 'websocket':AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), })
执行数据库的迁移命令
pythonmanage.pymigrate
要实现群聊功能,还需要准备redis
dockerrun-p6379:6379-dredis:2.8 pip3installchannels_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文件
fromasgiref.syncimportasync_to_sync fromchannels.generic.websocketimportWebsocketConsumer importjson classChatConsumer(WebsocketConsumer): defconnect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s'%self.room_name #Joinroomgroup async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() defdisconnect(self,close_code): #Leaveroomgroup async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) #ReceivemessagefromWebSocket defreceive(self,text_data): text_data_json=json.loads(text_data) message=text_data_json['message'] #Sendmessagetoroomgroup async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':message } ) #Receivemessagefromroomgroup defchat_message(self,event): message=event['message'] #SendmessagetoWebSocket self.send(text_data=json.dumps({ 'message':message }))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。