Django Channels从python websocket-client模块发送消息

时间:2017-10-29 12:48:40

标签: python django websocket django-channels channels

我有一个Django Channels服务器,我打算用它作为websocket服务器。我正在尝试使用https://pypi.python.org/pypi/websocket-client

向websocket发送消息

我可以通过握手阶段,可以看到终端中的连接日志。但是,当我向服务器发送消息时,我无法在consumer.py ws_message函数中看到打印消息。另外,我无法在前端看到该消息。如何向websocket发送消息?

consumers.py

from channels import Group
from game.models import Game


def ws_add(message, order_id):
    game = Game.objects.get(order__id=order_id)
    message.reply_channel.send({"accept": True})
    Group("game" + str(game.id)).add(message.reply_channel)

def ws_message(message, order_id):
    print message
    game = Game.objects.get(order__id=order_id)    
    Group("game" + str(game.id)).send({
        "text": message['text'],
    })

def ws_disconnect(message, order_id):
    game = Game.objects.get(order__id=order_id)    
    Group("game" + str(game.id)).discard(message.reply_channel)

send.py

from websocket import create_connection
ws = create_connection("ws://localhost:8000/game/1/stream")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
ws.close()

routing.py

from channels.routing import route
from game.consumers import ws_add, ws_message, ws_disconnect

channel_routing = [
    route("websocket.connect", ws_add, path="^/game/(?P<order_id>\d+)/stream/$"),
    route("websocket.receive", ws_message, path="^/game/(?P<order_id>\d+)/stream/$"),
    route("websocket.disconnect", ws_disconnect, path="^/game/(?P<order_id>\d+)/stream/$"),
]

0 个答案:

没有答案
相关问题