ich*_*kov 5 ruby websocket celluloid
我正在尝试使用基于赛璐珞(gem'celluloid-websocket-client')的Celluloid和Websocket客户端连接到远程websocket .这个客户端对我的主要优点是我可以以类方法的形式而不是块来使用回调.
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
Run Code Online (Sandbox Code Playgroud)
预期的产出是
"Websocket connection opened"
Run Code Online (Sandbox Code Playgroud)
但是,我根本没有得到任何输出.可能是什么问题呢?
我在用
gem 'celluloid-websocket-client', '0.0.2'
rails 4.2.1
ruby 2.1.3
Run Code Online (Sandbox Code Playgroud)
正如您在评论中注意到的那样,gem 没有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
Run Code Online (Sandbox Code Playgroud)
以上通过其他方法发送涟漪效果,例如,@handler用于保存调用actor,它也有发射器方法。就像我说的,我的版本与库存 gem 非常不同,因为我厌倦了它并重新设计了我的。但是之后:
Reel::IO::Client避免接近某些脑损伤。支持方面有一些令人兴奋的事情WebSocket,并且一个 gem 即将重构 websockets 的服务器和客户端实现。不再需要猴子补丁!
所有的 websocket 功能都是从抽象中提取出来Reel并与websocket-driver抽象相结合的,就像Reel::IO......在这两个::Server和::Client变种中一样。
有趣的是,这是由Rails哪个websockets正在远离EventMachineto提示的Celluloid::IO:
prealpha 在线预览:https : //github.com/celluloid/reel-io