Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of WebSocket online chat Room by Django

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces Django how to achieve WebSocket online chat room function, the article is very detailed, has a certain reference value, interested friends must read it!

Realization of WebSocket online chat Room by 1.Django

1.1 installation

Pip install channels==2.3

(saas) F:\ Desktop\ Python_Study\ CHS-Tracer\ saas > pip install channels==2.3

Looking in indexes: http://mirrors.aliyun.com/pypi/simple/

Collecting channels==2.3

Downloading

...

Successfully installed Automat-20.2.0 attrs-20.3.0 autobahn-21.3.1 channels-2.3.0

1.2 create a Django project

1.3 http routin

Url (r "^ chat/$", chat_view.chat, name= "chat"), # chat rooms

1.4 http View function

Def chat (request):

Return render (request, "chat.html")

1.5 settings add channels related configuration

INSTALLED_APPS = ['channels', # project is going to use channels as WebSocket] ASGI_APPLICATION = "saas.routing.application" # project name. Routing.application

Create routing.py (routing for websocket) and comsumers.py (view function for websocket)

1.7 websocket routin

#-*-coding:utf-8-*-# author: Cai Tuotuo, an IT pupil # time: 2021-4-23 1815 from channels.routing import ProtocolTypeRouter function: channels related routing from channels.routing import ProtocolTypeRouter, URLRouterfrom django.conf.urls import urlfrom web import consumersapplication = ProtocolTypeRouter ({"websocket": URLRouter ([url (r'^ chat/$', consumers.ChatConsumer),])})

1.8 websocket View function

#-*-coding:utf-8-*-# author: IT pupil Cai Tuotuo # time: 2021-4-23 18 channels related views from channels.exceptions import StopConsumerfrom channels.generic.websocket import WebsocketConsumer# defines a list Used to store the current online user CONSUMER_OBJECT_LIST = [] class ChatConsumer (WebsocketConsumer): def websocket_connect (self, message): "after the client browser sends the connection request, it will be triggered: param message:: return:"# the server receives the connection Send an encrypted string self.accept () # connection successful CONSUMER_OBJECT_LIST.append (self) def websocket_receive (self, message): "client browser sends a message to the server, this method automatically triggers: param message:: return:"print (" received the message. " , message) # the server returns a message to the client # self.send (text_data=message ["text"]) for obj in CONSUMER_OBJECT_LIST: obj.send (text_data=message ["text"]) def websocket_disconnect (self Message): "" client browser actively disconnects: param message:: return: "" # the server disconnects CONSUMER_OBJECT_LIST.remove (self) raise StopConsumer ()

1.9 Front-end code

Pre {display: block; padding: 9.5px; margin: 00 10px; font-size: 18px; line-height: 1.42857143; color: # 333; word-break: break-all; word-wrap: break-word; background-color: # 00aaaa; border-radius: 12px } send in online real-time chat room

Anonymous user:

The flag of var STATUS; / / whether to connect or not is var ws = new WebSocket ("ws://127.0.0.1:8000/chat/"); ws.onopen = function () {/ / the client automatically executes this method console.log ("connected successfully") after the handshake verification is successful. }; ws.onmessage = function msg (event) {var $item = $("# recordTemplate"). Find ('. Right-info'). Clone (); $item.find ('pre') .html (event.data); $("# content"). Append ($item);} Function sendMsg () {if (STATUS = = false) {swal ({title: "disconnected", text: "currently disconnected, refresh page to reconnect." });} else {ws.send ($("# txt") .val ()); $("# txt") .val ("");}} function closeLink () {ws.close (); STATUS = false; console.log ("disconnect") Swal ({text: "successfully disconnected, refresh the page and reconnect." });} 2. Effect display

3. Summary

Http protocol

Chat routing-- > chat View function

Access: just send a request from the browser

Websocket protocol

Chat routing-- > ChatConsumer (3 methods)

Accessing: new WebSocket object

The above is all the content of the article "how to achieve the function of WebSocket online chat room by Django". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report