websocket 在震动 Django Channels 后断开连接

问题描述 投票:0回答:1

我正在使用 django 和频道编写实时聊天

我的代码

consumers.py:

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        room_hash = self.scope["url_route"]["kwargs"]["room_hash"]
        #self.room_group_name = self.scope["url"]["kwargs"]["hash"]

        self.send(text_data = json.dumps({
            'type':'room_hash',
             'hash': room_hash
        }))

        chat_room = Room.objects.get(hash = hash)
        print(chat_room)
        self.accept({
            'type': 'websocket.accept'
        })

    def disconnect(self):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        print("Message is "+message)

路由

from django.urls import path
from . import consumers

ws_urlpatterns = [
    path('ws/<str:room_hash>/', consumers.ChatConsumer.as_asgi())
]

模板脚本:

{{room.hash|json_script:"json-roomhash"}}
<script type = "text/javascript">
   
    let room_hash = JSON.parse(document.getElementById("json-roomhash").textContent)
    let url = `ws://${window.location.host}/ws/${room_hash}/`

    const chatSocket = new WebSocket(url)

    chatSocket.onmessage = function(e){
        let data = JSON.parse(e.data)
        let hash = data.hash
        console.log(hash)
    }

    const form = document.querySelector("#form")
    console.log(form)
    form.addEventListener('submit', (e)=>{
        e.preventDefault()
        let message=  e.target.message.value
        chatSocket.send(JSON.stringify({
            'message':message
        }))
        form.reset()
    })

</script>

当我尝试通过房间的哈希值连接到 websocket 时,它会抛出此错误。

raise ValueError("Socket 尚未被接受,因此无法发送过来 它”)ValueError:套接字尚未被接受,因此无法通过它发送 应用程序内部异常:套接字尚未被接受,因此无法 发过来

django websocket django-channels
1个回答
0
投票

我只需添加异步和等待,代码如下所示:

class ChatConsumer(WebsocketConsumer):
    async def connect(self):
        room_hash = self.scope["url_route"]["kwargs"]["room_hash"]
        #self.room_group_name = self.scope["url"]["kwargs"]["hash"]

        await self.send(text_data = json.dumps({
            'type':'room_hash',
             'hash': room_hash
        }))

        chat_room = Room.objects.get(hash = hash)
        print(chat_room)
        await self.accept({
            'type': 'websocket.accept'
        })

    async def disconnect(self, code):
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name,
        )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        print("Message is "+message)

© www.soinside.com 2019 - 2024. All rights reserved.