【发布时间】:2017-04-06 14:06:48
【问题描述】:
我正在使用 Rails5 为我的应用程序创建一个 api 提供程序,并且我需要使用 websocket。
然后,我创建了一个非常简单的测试代码:
routes.rb
Rails.application.routes.draw do
mount ActionCable.server => '/cable'
get '/testbroad', to: 'messages#testbroad'
end
messages_channel.rb
class MessagesChannel < ApplicationCable::Channel
def subscribed
stream_from 'messages'
end
end
messages_controller.rb
class MessagesController < ApplicationController
def testbroad
ActionCable.server.broadcast('messages',
message: 'foo')
head :ok
end
end
然后,我使用 cURL 开始连接
➜ ~ curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: ws://localhost:3000/cable" http://localhost:3000/cable
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Location: ws://ws://localhost:3000/cable/cable
{"type":"welcome"}
这是工作!但是,当我尝试发送广播时......
➜ ~ curl http://localhost:3000/testbroad
Rails 的控制台显示成功,但是我在 cURL 中没有收到任何消息。为什么我没有收到消息“foo”?如何解决?
【问题讨论】:
标签: ruby-on-rails websocket actioncable