在ruby中保护Websocket客户端

时间:2015-04-22 15:09:39

标签: ruby ssl websocket faye

如何在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
    }

1 个答案:

答案 0 :(得分:0)

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

编辑由于Iodine继承了GRHttp的代码库并且正在积极开发,而且GRHttp不再处于活跃开发阶段,因此编辑了这个答案。