红宝石中的安全Websocket客户端

问题描述:

如何在Ruby中使用Faye-websocket创建安全(TLS)websocket客户端连接?红宝石中的安全Websocket客户端

我在我的脚本中使用faye/websocket gem。

require 'faye/websocket' 
    require 'eventmachine' 

    EM.run { 
     ws = Faye::WebSocket::Client.new('wss://aws.com/gateway',:ssl => { 
    :private_key_file => 'path/to/ssl.key', 
    :cert_chain_file => 'path/to/ssl.crt' 
    }, :headers => { 'Authorization' => 'Basic bXl1c2VyOm15cGFzc3dvcmQ='}) 

     ws.on :open do |event| 
     p [:open] 
     ws.send('Hello, world!') 
     end 

     ws.on :message do |event| 
     p [:message, event.data] 
     end 

     ws.on :close do |event| 
     p [:close, event.code, event.reason] 
     ws = nil 
     end 
    } 
+1

你在问'wss',那么你会得到它吗? – tadman

+1

不,现在写我得到: - 抛出'std :: runtime_error'实例后终止 什么():加密不可用在此事件机上 此应用程序已请求运行时终止它在一个不寻常的办法。 有关更多信息,请联系应用程序的支持团队。 –

+0

我有工作websocket服务器,只允许安全连接。 –

编辑2018

这个答案已经过时。

碘服务器被重写为C扩展,Websocket客户端和SSL/TLS层都没有在Ruby中实现(SSL/TLS隧道是目前实现加密的推荐方式)。


您可以使用可能使用Iodine's websocket client如果它是一个简单的连接(你可以添加查询参数,cookie和头请求,如果需要的话)......博览会的通知,我是碘的作者宝石。

它应该是简单:

# load the Http extension which includes a websocket client and server 
require 'iodine/http' 
# As long as Iodine.protocol isn't a Class, Iodine will only perform tasks 
Iodine.protocol = :timers 

# We will use this as our 'on_open' callback. 
on_open_proc = Proc.new do 
    puts 'Connection opened' 
    # `#write` is defined in the WebsocketClient 
    # This Proc runs within the instance's context. 
    # It's like defining a method in a subclass. 
    write 'Hello World!' 
end 
# We will use this as our 'on_message(data)' callback. 
on_message_proc = Proc.new {|data| puts data } 
# We will use this as our 'on_close' callback. 
# It's only called if the connection isn't automatically renewed. 
# In our case, unless the server shuts down, it won't be called. 
on_close_proc = Proc.new { puts "Connection wasn't renewed..." } 
# We will use this for "polling" data. 
on_timer_proc = Proc.new { write "The time is #{Time.now}" } 

# test client: 
Iodine::Http.ws_connect 'wss://echo.websocket.org', 
     on_message: on_message_proc, 
     on_open: on_open_proc, 
     on_close: on_close_proc, 
     every: 5, send: on_timer_proc, 
     renew: 5, 
     cookies: {'my_cookie' => 'value of my cookie'} #, 
     # ssl_key: 'key_data', ssl_cert: 'cert_data' 

# If you are running Iodine within irb, use `exit`: 
exit 

# If you are running Iodine within an existing server application, 
# you will have to force it to start while your script is running: 
# Iodine.force_start! 

WebSocket的回声服务器回答我的SSL ......所以我希望这会帮助你。

编辑由于碘继承了GRHttp的代码库,并且处于活跃的开发阶段,而GRHttp不再处于活跃的开发阶段,所以编辑了这个答案。