python - Django channel ; ECHO 示例不起作用

标签 python django django-channels

消费者文件

def ws_message(message):
    # ASGI WebSocket packet-received and send-packet message types
    # both have a "text" key for their textual data.
    message.reply_channel.send({
        "text": message.content['text'],
    })

路由文件

from channels.routing import route
from myapp.consumers import ws_message

channel_routing = [
    route("websocket.receive", ws_message),
]

我正在运行什么。

socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
    alert(e.data);
}
socket.onopen = function() {
    socket.send("hello world");

if (socket.readyState == WebSocket.OPEN) socket.onopen();

它什么也没做。我见过其他类似的问题,他们都说要降级到 16.2。好吧,我这样做了,但随后 runserver 开始出现无法导入 IProtocol 的问题。有没有解决这个问题的方法,或者我应该不使用 channel 并尝试其他方法?

最佳答案

在您的 consumers.py 文件中添加以下方法...

@channel_session_user_from_http
def ws_connect(message):


    message.reply_channel.send({"accept": True})
    room = message.content['path'].strip("/")
    message.channel_session['room'] = room
    Group("chat-%s" % room).add(message.reply_channel)

@channel_session
def ws_message(message):
Group("chat-%s" % message.channel_session['room']).send(content={
            'text': json.dumps({
                'message': message.content['text'],
                'data': hi,
            # "text": message['text'],
            # "text": str(serializers.data),
            })  })

@channel_session_user
def ws_disconnect(message):
    Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)

关于python - Django channel ; ECHO 示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44040825/

相关文章:

django - “用户”对象没有属性is_authenticated

python - Django 休息 : Uploading and serializing multiple images

html - Django REST 可浏览 API 模板更改

python - 如何使用 Django Channels 多线程 AsyncConsumer

django - 使用 Django 启动和停止定期后台任务

python - NBT Parser Minecraft mca 文件不是 gzipped 文件错误

python - 从 pandas 数据框中的多行中提取非 nan 值

python - 使用Python进行全文搜索

python - 我怎样才能 "zip sort"并行 numpy 数组?

python - Django channel Redis : Exception inside application: Lock is not acquired