2
我嘗試使用ActionCable在我的Rails應用程序和傳統的html頁面之間創建一個websocket。使用遠程起源的ActionCable
我只能在我的js腳本中使用「訂閱」,如果我嘗試說話命令,我得到一個錯誤: "Received unrecognized command in {"command"=>"speak", "identifier"=>"{\"channel\":\"StreamChannel\",\"content\":\"Hi everyone !\"}"}"
。
我的代碼:(https://gist.github.com/fclement21/ebd3be213f1fa5746321bd75284601b0)
JS
var ws = new WebSocket("ws://localhost:3000/cable");
var id = { channel: 'StreamChannel'};
var sub_cmd = {
command: 'subscribe',
identifier: JSON.stringify(id)
}
ws.onclose = function() { // thing to do on close
};
ws.onerror = function() { // thing to do on error
};
ws.onmessage = function(e) { // thing to do on message
data = JSON.parse(e.data);
console.log(data);
if(data.message.status == "200"){
var id_test = { channel: 'StreamChannel', content: "Hi everyone !"};
var stream_id = {
command: 'speak',
identifier: JSON.stringify(id_test)
}
ws.send(JSON.stringify(stream_id));
}
};
ws.onopen = function(e) {
ws.send(JSON.stringify(sub_cmd));
};
我Stream_channel.rb
class StreamChannel < ApplicationCable::Channel
def subscribed
stream_from "stream_test"
ActionCable.server.broadcast "stream_test", message: "You are now connected !", status: 200
end
def speak
ActionCable.server.broadcast "stream_test", message: "Your message has been sended", status: 200
end
end
你有沒有想過這個? – andrewoodleyjr