gpt4 book ai didi

python - 停留在 AsyncWebsocketConsumer 实现

转载 作者:IT王子 更新时间:2023-10-29 06:16:15 26 4
gpt4 key购买 nike

我正在尝试开发一个消费者(AsyncWebsocketConsumer 类型),它将与 websocket 连接并使用 JavaScript 对前端进行更改。我未能实现的第一件事是消费者的功能(连接、发送、断开连接)。此外,使用 Redis。

我的 settings.py

ASGI_APPLICATION = "myapp.routing.application"

CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('localhost', 6379)],
},
}
}


而我的 routing.py

application = ProtocolTypeRouter({
"channel": ChannelNameRouter({
"example": ExampleConsumer,
}),
})

最后,我的 consumers.py

class ExampleConsumer(AsyncWebsocketConsumer):

async def connect(self,msg):
# Called on connection.
# To accept the connection call:
await self.accept()
print('Channel connected')

当我尝试:

channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)('example', {'type': 'connect'})

这样我就可以调用 connect 并查看让我知道套接字已连接的连接消息,然后继续发送消息,我得到:

raise NotImplementedError("You must implement application_send()") You must implement application_send()

我很确定我误解了很多东西,但我一直在寻找如何解决这个问题,但我找不到对我的案例有用的东西,比如示例或好的文档,所以无论有什么帮助都会不胜感激!

最佳答案

您使用的 ChannelLayers 有误。它们用于在应用程序的不同实例之间进行通信。不适用于实际建立 WebSocket 连接。

试试这个:

settings.py

ASGI_APPLICATION = "myapp.routing.application" # make sure your project is called 'myapp' ;-)

路由.py

application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
path('ws/example/', consumers.ExampleConsumer),
])
),
})

消费者.py

class ExampleConsumer(AsyncWebsocketConsumer):

async def connect(self,msg):
# Called on connection.
# To accept the connection call:
await self.accept()
print('Channel connected')

async def receive(self, data):
# do something with data
print(data)
# send response back to connected client
await self.send('We received your message')

您可以使用 Simple Websocket Client测试你的 ws-endpoint。

  1. 连接到 http://localhost:8000/ws/example/ :您应该在控制台上看到“ channel 已连接”,以及客户端已连接的消息。
  2. 发送带有一些数据的请求。此数据应记录在控制台中,您将收到返回给客户的响应。

希望这有助于您入门。

关于python - 停留在 AsyncWebsocketConsumer 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57557355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com