不断地从服务器向客户端发送数据 [英] Constantly send data to client from server

查看:47
本文介绍了不断地从服务器向客户端发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个示例.

如您所见,某种event 不断地被发送到客户端.我想在 consumers.py 中使用 Django-Channels 来模仿这个.这是我所拥有的简化版本:

As you can see, some sort of event is constantly being sent to the client. I want to imitate this using Django-Channels, inside consumers.py. Here's a simplified version of what I have:

class ChatConsumer(AsyncConsumer):
    async def ws_connect(self, event):
        self.send = get_db_object()

        ....

        await self.send({
            "type": "websocket.accept"
        })

    # I need to CONSTANTLY receive & send data
    async def ws_receive(self, event):

        obj = ...# query DB and get the newest object

        json_obj = {
            'field_1': obj.field_1,
            'field_2': obj.field_2,
        }

        await self.send({
            "type": "websocket.send",
            "text": json.dumps(json_obj)
        })


    @database_sync_to_async
    def get_db_object(self, **kwargs):
        return Some_Model.objects.get(**kwargs)[0]

在这里,我希望我的 Django 后端不断:

Here, I want my Django backend to constantly:

  1. 查询数据库
  2. 从数据库接收对象
  3. 将接收到的 obj 作为 event
  4. 发送到前端 WebSocket
  1. Query DB
  2. Receive obj from DB
  3. Send the received obj to Front-End WebSocket as event

我怎样才能做到这一点?重要的是我需要持续向客户端发送数据.

How can I achieve this? The important thing is that I need to CONSTANTLY send data to the client.

互联网上的大多数 Django-Channels 资源仅涵盖聊天应用程序,它们不一定会不断地向客户端发送数据.我找不到任何可以完成这项工作的工作代码.

Most of the Django-Channels resources on the internet cover only Chat Apps, which don't necessarily constantly send data to the client. I couldn't find any working code that does this job.

请不要再推荐 Redis 或频道文档……或者一些缺乏良好文档的随机 3rd 方库……推荐很容易,但很难实现.例如,我发现有人推荐 Snorky,但它确实缺乏关于如何实现它的文档.

Please, no more recommendation for Redis or channels documentation... or some random 3rd party libraries that lacks good documentation... It's easy to recommend but hard to implement. For example, I found someone recommending Snorky, but it really lacks documentation on how to implement it.

不过,如果有专门做这项工作的网站,我可能会看看它,即使它不使用 Django-Channels.

However, if there's a website that specifically does this job, I might take a look at it, even if it doesn't use Django-Channels.

推荐答案

consumers.py

import asyncio
from channels.consumer import AsyncConsumer

class ChatConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        print("connected", event)
        await self.send({
            "type": "websocket.accept"
        })

        while True:
            await asyncio.sleep(2)

            obj = # do_something (Ex: constantly query DB...)
 
            await self.send({
                'type': 'websocket.send',
                'text': # obj,
            })

    async def websocket_receive(self, event):
        print("receive", event)

    async def websocket_disconnect(self, event):
        print("disconnected", event)

jQuery

var loc = window.location;
var wsStart = 'ws://';
if (loc.protocol == 'https:') {
    wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname;

var socket = new WebSocket(endpoint);

socket.onmessage = function(e){
    console.log("message", e);
};
socket.onopen = function(e){
    console.log("open", e);
};
socket.onerror = function(e){
    console.log("error", e)
};
socket.onclose = function(e){
    console.log("close", e)
};

您只需修改obj 并发送即可.您可以根据需要扩展此功能.所以,现在我有兴趣在我的 PostgreSQL 中获取最新插入的行并将该行注入我的 WebSocket.我可以每 2 秒查询一次我的数据库,因为它是由 await asyncio.sleep(2) 指定的,并将其注入前端套接字.

All you need to do is just modify obj and send it. You can extend this function as much as you want. So, right now I'm interested in getting the latest inserted row in my PostgreSQL and injecting that row into my WebSocket. I can query my DB every 2 seconds as it was specified by await asyncio.sleep(2), and inject it into the Front-End socket.

这篇关于不断地从服务器向客户端发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆