在ruby中保护Websocket客户端

如何使用Ruby中的Faye-websocket建立安全(TLS)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 } 

编辑2018

这个答案已经过时了。

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


你可以使用Iodine的websocket客户端,如果它是一个简单的连接(你可以在请求中添加查询参数,cookie和标题,如果你需要它们)……公平的通知,我是Iodine gem的作者。

应该很简单:

 # 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 echo服务器在SSL上回答我…所以我希望这会对你有所帮助。

编辑这个答案是在Iodineinheritance了GRHttp的代码库并且处于积极开发之后编辑的,而GRHttp不再处于积极开发阶段。