SoFunction
Updated on 2024-11-19

Django Websocket Websocket broadcast, peer-to-peer send messages code

1.DjangorealizationWebsocket

utilizationDjangoto realizeWebsocketThere are many ways to serve you and here we recommend the latest technology.Channelslibrary to implement the

1.1. InstallationDjangoChannels

ChannelsmountingIf you areWindowsoperating system, then the necessary condition isPython3.7

pip install channels

1.2. ConfigurationDjangoChannels

1.Create a projectChannelsReady

django-admin startprobject ChannelsReady

2. In the project'sCreate a new file in the same level directory

# 
from  import ProtocolTypeRouter

application = ProtocolTypeRouter({
 # Temporarily empty
})

3. In the project configuration filewrite in

INSTALLED_APPS = [
 'channels'
]

ASGI_APPLICATION = ""

1.3. Launch withChannelsofferedASGI(used form a nominal expression)Djangosports event

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python migrate' to apply them.
February 01, 2020 - 17:27:13
Django version 3.0.2, using settings ''
Starting ASGI/Channels version 2.4.0 development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.

It's obvious to seeASGI/ChannelsThis completes the startup.

1.4. CreationWebsocketservice

1. Create a new applicationchats

python  startapp chats

2. Ininitial recognitionchats

INSTALLED_APPS = [
 'chats',
 'channels'
]

3. InchatsNew file in the application

from  import WebsocketConsumer
# In addition to the WebsocketConsumer, there is also the
# JsonWebsocketConsumer
# AsyncWebsocketConsumer
# AsyncJsonWebsocketConsumer
# WebsocketConsumer vs. JsonWebsocketConsumer is that there is an additional method that can automatically handle JSON.
# AsyncWebsocketConsumer and AsyncJsonWebsocketConsumer also have an additional JSON method
# AsyncWebsocketConsumer vs. WebsocketConsumer is the point.
# The name doesn't seem too hard to understand Async is just asynchronous with async / await
# Yes, there's nothing wrong with that, but the only thing that's different about them for us is probably the length of the name, the usage is exactly the same #
# What's great is that the base class is the same, and the methods of that base class are also Async asynchronous #

class ChatService(WebsocketConsumer):
 # When Websocket creates a connection
 def connect(self):
 pass
 
 # When the websocket receives a message
 def receive(self, text_data=None, bytes_data=None):
 pass
 
 # When a websocket disconnection occurs
 def disconnect(self, code):
 pass

1.5.WebsocketHandle object addition routing

1. InchatsIn the application, the new

from  import path
from  import ChatService
websocket_url = [
 path("ws/",ChatService)
]

2. Back to the projectAdd to the fileASGIin-HTTPRequest processing

from  import ProtocolTypeRouter,URLRouter
from  import websocket_url

application = ProtocolTypeRouter({
 "websocket":URLRouter(
 websocket_url
 )
})

Summary:

  • downloading
  • Register to the app
  • Register the routes used by channels in the same level of directory ----->.
  • will be registered to
  • Register the routes in the
  • Write to handle websocket requests
<template>
 <div>
 <input type="text" v-model="message">
 <p><input type="button" @click="send" value="Send."></p>
 <p><input type="button" @click="close_socket" value="Close."></p>
 </div>
</template>


<script>
export default {
 name:'websocket1',
 data() {
 return {
  message:'',
  testsocket:''
 }
 },
 methods:{
 send(){
  
 // send send message
 // close Close the connection

  ()
   = (res) => {
  ("WS return results",);  
  }

 },
 close_socket(){
  ()
 }

 },
 mounted(){
  = new WebSocket("ws://127.0.0.1:8000/ws/") 


 // onopen Defines the function to use when opening.
 // onclose Defines the function to use when closing.
 // onmessage Defines the function to use when receiving data.
 //  = function(){
 // ("Starting socket connection")
 // },
 //  = function(){
 // ("The socket connection is closed.")
 // }
 }
}
</script>

3. Broadcast messages

3.1 Clients remain unchanged and multiple clients are open at the same time

3.2 Server-side storage of each linked object

socket_list = []

class ChatService(WebsocketConsumer):
 # When Websocket creates a connection
 def connect(self):
 ()
 socket_list.append(self)


 # When the websocket receives a message
 def receive(self, text_data=None, bytes_data=None):
 print(text_data) # Print received data
 for ws in socket_list: # Iterate over all WebsocketConsumer objects
 (text_data) # For each of theWebsocketConsumerObject sends data

4. Peer-to-peer messaging

4.1 The client splices the username into the url and specifies the object to be sent in the sent message

<template>
 <div>
 <input type="text" v-model="message">
 <input type="text" v-model="user">

 <p><input type="button" @click="send" value="Send."></p>
 <p><input type="button" @click="close_socket" value="Close."></p>
 </div>
</template>


<script>
export default {
 name:'websocket1',
 data() {
 return {
  message:'',
  testsocket:'',
  user:''
 }
 },
 methods:{
 send(){
  
 // send send message
 // close Closes the connection
  var data1 = {"message":,"to_user":}
  
  ((data1))
   = (res) => {
  ("WS return results",);  
  }

 },
 close_socket(){
  ()
 },
 generate_uuid: function() {
  var d = new Date().getTime();
  if ( && typeof  === "function") {
  d += (); //use high-precision timer if available
  }
  var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
  /[xy]/g,
  function(c) {
  var r = (d + () * 16) % 16 | 0;
  d = (d / 16);
  return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
  }
  );
  return uuid;
 },

 },
 mounted(){
 var username = this.generate_uuid();
 (username)
  = new WebSocket("ws://127.0.0.1:8000/ws/"+ username +"/") 
 ()

 	 = (res) => {
  ("WS return results",);  
  }
 	
 // onopen Defines the function to use when opening.
 // onclose Defines the function to use when closing.
 // onmessage Defines the function to use when receiving data.
 //  = function(){
 // ("Starting socket connection")
 // },
 //  = function(){
 // ("The socket connection is closed.")
 // }
 }
}
</script>

4.2 The server stores the username and websocketConsumer, and then sends a message to the corresponding user

from  import WebsocketConsumer
user_dict ={}
list = []
import json
class ChatService(WebsocketConsumer):
 # When Websocket creates a connection
 def connect(self):
 ()
 username = ("url_route").get("kwargs").get("username")
 user_dict[username] =self
 print(user_dict)

 # (self)


 # When the websocket receives a message
 def receive(self, text_data=None, bytes_data=None):
 data = (text_data)
 print(data)
 to_user = ("to_user")
 message = ("message")

 ws = user_dict.get(to_user)
 print(to_user)
 print(message)
 print(ws)
 (text_data)


 # When a websocket disconnection occurs
 def disconnect(self, code):
 pass

summarize

This article on Django Websocket broadcast, point to point to send a message to this article , more related to Django Websocket broadcast, point to point to send a message to search for my previous posts or continue to browse the following related articles I hope you will support me in the future more !