Python Django频道:与websocket相同的另一个聊天消费者
所以我正在做一个使用WebSocket的项目,它工作得非常好。我决定将websocket连接包含到另一个页面,因此我决定将另一个页面添加到我的routing.py中,并且我为另一个页面创建了另一个ChatConsumer,问题是我发布了两个不同的连接,如何使我的另一个chatconsumer与另一个chatconsumer相同,以使此连接与websocket连接相同 这是我的consumer.py:Python Django频道:与websocket相同的另一个聊天消费者,python,django,websocket,django-channels,Python,Django,Websocket,Django Channels,所以我正在做一个使用WebSocket的项目,它工作得非常好。我决定将websocket连接包含到另一个页面,因此我决定将另一个页面添加到我的routing.py中,并且我为另一个页面创建了另一个ChatConsumer,问题是我发布了两个不同的连接,如何使我的另一个chatconsumer与另一个chatconsumer相同,以使此连接与websocket连接相同 这是我的consumer.py: import asyncio import json from django.contrib.
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from .models import Thread, ChatMessage
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("connected", event)
other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
# print(other_user, me)
thread_obj = await self.get_thread(me, other_user)
self.thread_obj = thread_obj
chat_room = f"thread_{thread_obj.id}"
self.chat_room = chat_room
await self.channel_layer.group_add(
chat_room,
self.channel_name
)
await self.send({
"type": "websocket.accept"
})
# await asyncio.sleep(10)
async def websocket_receive(self, event):
# when a message is received from the websocket
print("receive", event)
front_text = event.get('text', None)
if front_text is not None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get('message')
user = self.scope['user']
username = 'default'
if user.is_authenticated:
username = user.username
myResponse = {
'message': msg,
'username': username,
}
await self.create_chat_message(user, msg)
# broadcast the message event to be send
await self.channel_layer.group_send(
self.chat_room,
{
"type": "chat_message",
"text": json.dumps(myResponse)
}
)
async def chat_message(self, event):
# sends the actual message
await self.send({
"type": "websocket.send",
"text": event['text']
})
async def websocket_disconnect(self, event):
# when the socket connects
print("disconnected", event)
@database_sync_to_async
def get_thread(self, user, other_username):
return Thread.objects.get_or_new(user, other_username)[0]
@database_sync_to_async
def create_chat_message(self, me, msg):
thread_obj = self.thread_obj
return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)
也许你会说“为什么不在路由中使用chatconsumer?”,我不能使用chatconsumer,因为它给出了这个错误
File "./consumers.py" in websocket_connect
other_user = self.scope['url_route']['kwargs']['username']
'username'
感谢您的帮助如果您想让多个使用者可以访问同一个websocket连接,则需要使用
多路复用
解决方案查看:如果您想让多个使用者可以访问同一个websocket连接,则需要使用多路复用
解决方案查看:能否添加导致错误的路由配置?使用路由可能比较简单。您可以添加导致错误的路由配置吗?使用路由可能会很简单。我不太了解通道多路复用,我如何添加它?也许我不了解你的问题?您是否打开了两个浏览器选项卡,或者您希望同一个浏览器选项卡有两个不同的使用者?我不太了解频道复用,如何添加?可能我不了解您的问题?您是否打开了两个浏览器选项卡,还是希望同一个浏览器选项卡有两个不同的使用者?