6

I'm trying to connect to remote websocket using Celluloid and Websocket client based on celluloid (gem 'celluloid-websocket-client'). The main advantage of this client for me is that I can use callbacks in the form of class methods instead of blocks.

require 'celluloid/websocket/client'
class WSConnection
  include Celluloid

  def initialize(url)
    @ws_client = Celluloid::WebSocket::Client.new url, Celluloid::Actor.current
  end

  # When WebSocket is opened, register callbacks
  def on_open
    puts "Websocket connection opened"
  end

  # When raw WebSocket message is received
  def on_message(msg)
    puts "Received message: #{msg}"
  end

  # When WebSocket is closed
  def on_close(code, reason)
    puts "WebSocket connection closed: #{code.inspect}, #{reason.inspect}"
  end

end

m = WSConnection.new('wss://foo.bar')

while true; sleep; end

The expected output is

"Websocket connection opened"

However, I don't get any output at all. What could be the problem?

I am using

gem 'celluloid-websocket-client', '0.0.2'
rails 4.2.1
ruby 2.1.3
4

1 回答 1

5

正如您在评论中注意到的那样,宝石没有SSL支持。这就是麻烦。为了解释答案,这里有一个解决方案,以及未来的一些后续步骤:


[现在]覆盖方法Celluloid::WebSocket::Client::Connection

SSL这是一个为当前 gem提供支持的示例注入。我的实际上是经过高度修改的,但这向您展示了基本解决方案:

def initialize(url, handler=nil)
  @url = url
  @handler = handler || Celluloid::Actor.current
  #de If you want an auto-start:
  start
end

def start
  uri = URI.parse(@url)
  port = uri.port || (uri.scheme == "ws" ? 80 : 443)
  @socket.close rescue nil
  @socket = Celluloid::IO::TCPSocket.new(uri.host, port)
  @socket = Celluloid::IO::SSLSocket.new(@socket) if port == 443
  @socket.connect
  @client = ::WebSocket::Driver.client(self)
  async.run
end

上面通过其他方法发送涟漪效果,例如,@handler用于保存调用actor,它也有发射器方法。就像我说的,我的版本与普通 gem 非常不同,因为我厌倦了它并重新设计了我的版本。但是之后:


[ 很快 ] 使用Reel::IO::Client并避免接近某些脑损伤。

支持方面正在发生令人兴奋的事情WebSocket,并且正在重构 websockets 的服务器和客户端实现的 gem。不再需要猴子补丁!

所有websocket功能都从抽象中提取并Reelwebsocket-driver抽象相结合,如Reel::IO...::Server::Client

有趣的是,这是由于websocketsRails正在远离EventMachineto提示的:Celluloid::IO

prealpha 在线预览:https ://github.com/celluloid/reel-io

于 2015-07-15T01:01:14.910 回答