消费者档案
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 ---问题。有没有解决这个问题,或者我应该不使用频道,并尝试别的吗?
答案 0 :(得分:1)
在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)