Websocket无法连接到ActionController :: Live - 以200失败

时间:2015-08-18 19:27:02

标签: ruby-on-rails

class MessagesController < ApplicationController

  include ActionController::Live

  def events
    response.headers['Content-Type'] = 'text/event-stream'
    sse = SSE.new response.stream
    redis = Redis.new
    redis.subscribe(redis_channel) do |on|
      on.message do |event, data|            
        sse.write(data, event: 'messages.create')
      end
    end
    #render nothing: true 
  rescue IOError
    # disco bro!
  ensure
    redis.quit
    sse.close
  end
end

// also tried without the SSE.new, so just plain response.stream.write(data)

我的Javascript很简单

var socket = new WebSocket("ws://localhost:3000/events")
socket.onmessage = function (event) {
  console.log(event);      
}

当我在浏览器中调用/events并发送一些消息时 - 输出。但如果我们用JS连接套接字,我们就得到

WebSocket connection to 'ws://localhost:3000/petra/events' failed: 
Error during WebSocket handshake: Unexpected response code: 200

任何人都可以点亮我吗?我们是否遗漏了某些东西,或者我对我想要做的事情有错误的理解。

1 个答案:

答案 0 :(得分:0)

WebSockets和服务器发送事件是不同的协议,无法以您尝试的方式进行操作。

SSE的主要js API为EventSource(url)introductory article)。

如果您想要双向通信,则可以将服务器端切换为使用WebSockets。对于ruby on rails,websocket-rails是一个很受欢迎的库。