如何在没有JS的情况下在ActionCable Channel中接收数据?
How to receive data in ActionCable Channel without JS?
我正在编写一个 Rails 应用程序,它使用 WebSockets 与其他机器通信(在此过程中没有浏览器和客户端逻辑)。我有一个频道:
class MachinesChannel < ApplicationCable::Channel
def subscribed
...
end
def unsubscribed
...
end
def handle_messages
...
end
end
我所知道的接收数据的唯一方法是 JavaScript 客户端:
ActionCable.createConsumer('/cable').subscriptions.create 'MachinesChannel',
received: (message) ->
@perform('handle_messages')
我可以通过 @perform()
方法从 JS 调用服务器端方法。
有没有办法省略JS部分,直接处理MachinesChannel
中传入的数据?
理想情况是让 handle_messages
方法接受一个 data
参数,并在传入数据上调用此方法。
查看 ActionCable
源代码后,我得到了以下解决方案。您只需在 MachinesChannel
中创建一个您想要调用的方法,例如handle_messages(data)
。然后,在连接到您的 websocket 的客户端中,您需要按以下格式发送消息(ruby 中的示例):
id = { channel: 'MachinesChannel' }
ws = WebSocket::Client::Simple.connect(url)
ws.send(JSON.generate(command: 'message', identifier: JSON.generate(id), data: JSON.generate(action: 'handle_messages', foo: 'bar', biz: 'baz')))
action
必须是您要在 MachinesChannel
中调用的方法的名称。其余的键值是你想要的任何东西。这是您可以在 ActionCable
频道收到的日期。
最近发布了 gem action_cable_client,它似乎非常适合这种用法。没用过,不知道效果如何
而不是:
def handle_messages
...
end
这对我有用:
def receive(data)
puts data
...
end
我正在编写一个 Rails 应用程序,它使用 WebSockets 与其他机器通信(在此过程中没有浏览器和客户端逻辑)。我有一个频道:
class MachinesChannel < ApplicationCable::Channel
def subscribed
...
end
def unsubscribed
...
end
def handle_messages
...
end
end
我所知道的接收数据的唯一方法是 JavaScript 客户端:
ActionCable.createConsumer('/cable').subscriptions.create 'MachinesChannel',
received: (message) ->
@perform('handle_messages')
我可以通过 @perform()
方法从 JS 调用服务器端方法。
有没有办法省略JS部分,直接处理MachinesChannel
中传入的数据?
理想情况是让 handle_messages
方法接受一个 data
参数,并在传入数据上调用此方法。
查看 ActionCable
源代码后,我得到了以下解决方案。您只需在 MachinesChannel
中创建一个您想要调用的方法,例如handle_messages(data)
。然后,在连接到您的 websocket 的客户端中,您需要按以下格式发送消息(ruby 中的示例):
id = { channel: 'MachinesChannel' }
ws = WebSocket::Client::Simple.connect(url)
ws.send(JSON.generate(command: 'message', identifier: JSON.generate(id), data: JSON.generate(action: 'handle_messages', foo: 'bar', biz: 'baz')))
action
必须是您要在 MachinesChannel
中调用的方法的名称。其余的键值是你想要的任何东西。这是您可以在 ActionCable
频道收到的日期。
最近发布了 gem action_cable_client,它似乎非常适合这种用法。没用过,不知道效果如何
而不是:
def handle_messages
...
end
这对我有用:
def receive(data)
puts data
...
end