WebSocket在摇动Django Channels后断开连接

qcuzuvrc  于 2023-11-19  发布在  Go
关注(0)|答案(1)|浏览(125)

我编码一个真实的时间聊天使用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 has not been accepted,so cannot send over it”)ValueError:Socket has not been accepted,so cannot send over it应用程序内部异常:Socket has not been accepted,so cannot send over it

fhity93d

fhity93d1#

我只需要添加一个pwc和await,代码看起来像这样:

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)

字符串

相关问题