2016-08-25 58 views
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 
+0

你有沒有想過這個? – andrewoodleyjr

回答

2

我能拜弄明白自述on this GitHub repo。看來ActionCable使用「消息」命令來實際發送內容。要添加的關鍵是您還需要提供的JSON中的「action」屬性。以你的發佈代碼爲例:

if(data.message.status == "200"){ 
    var id_test = { channel: 'StreamChannel' }; 
    var stream_id = { 
    command: 'message', 
    identifier: JSON.stringify(id_test), 
    data: JSON.stringify({action: "speak", content: "Hi everyone !"}) 
    } 
    ws.send(JSON.stringify(stream_id)); 
} 
相關問題