当前位置:首页 >> 脚本专栏

基于django channel实现websocket的聊天室的方法示例

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
        }))
    
    

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。