最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對點(diǎn)發(fā)送消息的代碼

 更新時間:2020年06月03日 11:20:06   作者:初心ya  
這篇文章主要介紹了Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對點(diǎn)發(fā)送消息,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1.Django實(shí)現(xiàn)Websocket

使用Django來實(shí)現(xiàn)Websocket服務(wù)的方法很多在這里我們推薦技術(shù)最新的Channels庫來實(shí)現(xiàn)

1.1.安裝DjangoChannels

Channels安裝如果你是Windows操作系統(tǒng)的話,那么必要條件就是Python3.7

pip install channels

1.2.配置DjangoChannels

1.創(chuàng)建項(xiàng)目ChannelsReady

django-admin startprobject ChannelsReady

2.在項(xiàng)目的settings.py同級目錄中,新建文件routing.py

# routing.py
from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({
 # 暫時為空
})

3.在項(xiàng)目配置文件settings.py中寫入

INSTALLED_APPS = [
 'channels'
]

ASGI_APPLICATION = "ChannelsReady.routing.application"

1.3.啟動帶有Channels提供的ASGIDjango項(xiàng)目

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 manage.py migrate' to apply them.
February 01, 2020 - 17:27:13
Django version 3.0.2, using settings 'ChannelsReady.settings'
Starting ASGI/Channels version 2.4.0 development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.

很明顯可以看到ASGI/Channels,這樣就算啟動完成了

1.4.創(chuàng)建Websocket服務(wù)

1.創(chuàng)建一個新的應(yīng)用chats

python manage.py startapp chats

2.在settings.py中注冊chats

INSTALLED_APPS = [
 'chats',
 'channels'
]

3.在chats應(yīng)用中新建文件chatService.py

from channels.generic.websocket import WebsocketConsumer
# 這里除了 WebsocketConsumer 之外還有
# JsonWebsocketConsumer
# AsyncWebsocketConsumer
# AsyncJsonWebsocketConsumer
# WebsocketConsumer 與 JsonWebsocketConsumer 就是多了一個可以自動處理JSON的方法
# AsyncWebsocketConsumer 與 AsyncJsonWebsocketConsumer 也是多了一個JSON的方法
# AsyncWebsocketConsumer 與 WebsocketConsumer 才是重點(diǎn)
# 看名稱似乎理解并不難 Async 無非就是異步帶有 async / await
# 是的理解并沒有錯,但對與我們來說他們唯一不一樣的地方,可能就是名字的長短了,用法是一模一樣的
# 最夸張的是,基類是同一個,而且這個基類的方法也是Async異步的

class ChatService(WebsocketConsumer):
 # 當(dāng)Websocket創(chuàng)建連接時
 def connect(self):
 pass
 
 # 當(dāng)Websocket接收到消息時
 def receive(self, text_data=None, bytes_data=None):
 pass
 
 # 當(dāng)Websocket發(fā)生斷開連接時
 def disconnect(self, code):
 pass

1.5.為Websocket處理對象增加路由

1.在chats應(yīng)用中,新建urls.py

from django.urls import path
from chats.chatService import ChatService
websocket_url = [
 path("ws/",ChatService)
]

2.回到項(xiàng)目routing.py文件中增加ASGIHTTP請求處理

from channels.routing import ProtocolTypeRouter,URLRouter
from chats.urls import websocket_url

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

總結(jié):

  • 下載
  • 注冊到setting.py里的app
  • 在setting.py同級的目錄下注冊channels使用的路由----->routing.py
  • 將routing.py注冊到setting.py
  • 把urls.py的路由注冊到routing.py里
  • 編寫wsserver.py來處理websocket請求
<template>
 <div>
 <input type="text" v-model="message">
 <p><input type="button" @click="send" value="發(fā)送"></p>
 <p><input type="button" @click="close_socket" value="關(guān)閉"></p>
 </div>
</template>


<script>
export default {
 name:'websocket1',
 data() {
 return {
  message:'',
  testsocket:''
 }
 },
 methods:{
 send(){
  
 // send 發(fā)送信息
 // close 關(guān)閉連接

  this.testsocket.send(this.message)
  this.testsocket.onmessage = (res) => {
  console.log("WS的返回結(jié)果",res.data);  
  }

 },
 close_socket(){
  this.testsocket.close()
 }

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


 // onopen 定義打開時的函數(shù)
 // onclose 定義關(guān)閉時的函數(shù)
 // onmessage 定義接收數(shù)據(jù)時候的函數(shù)
 // this.testsocket.onopen = function(){
 // console.log("開始連接socket")
 // },
 // this.testsocket.onclose = function(){
 // console.log("socket連接已經(jīng)關(guān)閉")
 // }
 }
}
</script>

3.廣播消息

3.1客戶端保持不變,同時打開多個客戶端

3.2服務(wù)端存儲每個鏈接的對象

socket_list = []

class ChatService(WebsocketConsumer):
 # 當(dāng)Websocket創(chuàng)建連接時
 def connect(self):
 self.accept()
 socket_list.append(self)


 # 當(dāng)Websocket接收到消息時
 def receive(self, text_data=None, bytes_data=None):
 print(text_data) # 打印收到的數(shù)據(jù)
 for ws in socket_list: # 遍歷所有的WebsocketConsumer對象
 ws.send(text_data) # 對每一個WebsocketConsumer對象發(fā)送數(shù)據(jù)

4.點(diǎn)對點(diǎn)消息

4.1客戶端將用戶名拼接到url,并在發(fā)送的消息里指明要發(fā)送的對象

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

 <p><input type="button" @click="send" value="發(fā)送"></p>
 <p><input type="button" @click="close_socket" value="關(guān)閉"></p>
 </div>
</template>


<script>
export default {
 name:'websocket1',
 data() {
 return {
  message:'',
  testsocket:'',
  user:''
 }
 },
 methods:{
 send(){
  
 // send 發(fā)送信息
 // close 關(guān)閉連接
  var data1 = {"message":this.message,"to_user":this.user}
  
  this.testsocket.send(JSON.stringify(data1))
  this.testsocket.onmessage = (res) => {
  console.log("WS的返回結(jié)果",res.data);  
  }

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

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

 	this.testsocket.onmessage = (res) => {
  console.log("WS的返回結(jié)果",res.data);  
  }
 	
 // onopen 定義打開時的函數(shù)
 // onclose 定義關(guān)閉時的函數(shù)
 // onmessage 定義接收數(shù)據(jù)時候的函數(shù)
 // this.testsocket.onopen = function(){
 // console.log("開始連接socket")
 // },
 // this.testsocket.onclose = function(){
 // console.log("socket連接已經(jīng)關(guān)閉")
 // }
 }
}
</script>

4.2服務(wù)端存儲用戶名以及websocketConsumer,然后給對應(yīng)的用戶發(fā)送信息

from channels.generic.websocket import WebsocketConsumer
user_dict ={}
list = []
import json
class ChatService(WebsocketConsumer):
 # 當(dāng)Websocket創(chuàng)建連接時
 def connect(self):
 self.accept()
 username = self.scope.get("url_route").get("kwargs").get("username")
 user_dict[username] =self
 print(user_dict)

 # list.append(self)


 # 當(dāng)Websocket接收到消息時
 def receive(self, text_data=None, bytes_data=None):
 data = json.loads(text_data)
 print(data)
 to_user = data.get("to_user")
 message = data.get("message")

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


 # 當(dāng)Websocket發(fā)生斷開連接時
 def disconnect(self, code):
 pass

總結(jié)

到此這篇關(guān)于Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對點(diǎn)發(fā)送消息的文章就介紹到這了,更多相關(guān)Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對點(diǎn)發(fā)送消息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中使用ipython的詳細(xì)教程

    Python中使用ipython的詳細(xì)教程

    ipython是一個非常流行的python解釋器,比python解釋器好用很多,本文重點(diǎn)給大家介紹Python中使用ipython的詳細(xì)教程,需要的朋友參考下吧
    2021-06-06
  • Python批量合并有合并單元格的Excel文件詳解

    Python批量合并有合并單元格的Excel文件詳解

    經(jīng)常使用Excel的用戶都知道,合并單元格的存在,這篇文章主要給大家介紹了關(guān)于利用Python如何批量合并有合并單元格的Excel文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。
    2018-04-04
  • Pytorch用Tensorboard來觀察數(shù)據(jù)

    Pytorch用Tensorboard來觀察數(shù)據(jù)

    這篇文章主要介紹了Pytorch用Tensorboard來觀察數(shù)據(jù),上一篇文章我們講解了關(guān)于Pytorch?Dataset的數(shù)據(jù)處理,這篇我們就來講解觀察數(shù)據(jù),下面具體相關(guān)資料,需要的朋友可以參考一下,希望對你有所幫助
    2021-12-12
  • python爬蟲http代理使用方法

    python爬蟲http代理使用方法

    在本篇文章里小編給大家整理的是一篇關(guān)于python爬蟲http代理使用方法相關(guān)內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)參考下。
    2021-09-09
  • Python3?DataFrame缺失值的處理方法

    Python3?DataFrame缺失值的處理方法

    這篇文章主要介紹了Python3?DataFrame缺失值的處理,包括缺失值的判斷缺失值數(shù)據(jù)的過濾及缺失值數(shù)據(jù)的填充,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • Python經(jīng)緯度坐標(biāo)轉(zhuǎn)換為距離及角度的實(shí)現(xiàn)

    Python經(jīng)緯度坐標(biāo)轉(zhuǎn)換為距離及角度的實(shí)現(xiàn)

    這篇文章主要介紹了Python經(jīng)緯度坐標(biāo)轉(zhuǎn)換為距離及角度的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Python爬蟲谷歌Chrome F12抓包過程原理解析

    Python爬蟲谷歌Chrome F12抓包過程原理解析

    這篇文章主要介紹了Python爬蟲谷歌Chrome F12抓包過程原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • python辦公之python編輯word

    python辦公之python編輯word

    這篇文章主要介紹了python辦公之python編輯word,文章我們以python操作word為例來介紹一些簡單的操作,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • 使用Python進(jìn)行數(shù)據(jù)清洗與存儲的基本方法

    使用Python進(jìn)行數(shù)據(jù)清洗與存儲的基本方法

    在爬蟲數(shù)據(jù)獲取完成后,數(shù)據(jù)往往是“原始”的,不適合直接使用,清洗和存儲是將爬取到的原始數(shù)據(jù)轉(zhuǎn)化為有用信息的關(guān)鍵步驟,本文將系統(tǒng)地介紹 Python 中進(jìn)行數(shù)據(jù)清洗與存儲的基本方法,幫助新手理解如何處理爬蟲數(shù)據(jù),使其更加適合分析和使用,需要的朋友可以參考下
    2024-11-11
  • python利用itertools生成密碼字典并多線程撞庫破解rar密碼

    python利用itertools生成密碼字典并多線程撞庫破解rar密碼

    這篇文章主要介紹了python利用itertools生成密碼字典并多線程撞庫破解rar密碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08

最新評論

元朗区| 马鞍山市| 宝丰县| 屏南县| 新疆| 商城县| 南木林县| 莱阳市| 高台县| 连江县| 华宁县| 永昌县| 紫云| 屯门区| 清河县| 金山区| 方城县| 弋阳县| 金沙县| 黔江区| 武定县| 康马县| 台山市| 惠州市| 华安县| 高邮市| 密云县| 平谷区| 蓬安县| 屏南县| 黔西| 凤山县| 洪泽县| 墨江| 华阴市| 新乡县| 遵化市| 西畴县| 浦城县| 泽普县| 佳木斯市|