Faye WebSockets - Part 2

Episode #25 by Teacher's Avatar David Kimura


Learn how to install and configure a thin server within a Linux environment hosting a Faye WebSocket application. This episode includes showing you how to server your WebSockets over a secure SSL connection.
rails websockets messaging notifications 6:46



# bash
    sudo apt-get install git
    ruby -v
    git clone https://github.com/driftingruby/faye-simple.git 
    sudo mv faye-simple/ /opt/faye
    cd /opt/faye
    gem install bundler
    ll /home/ws/.rvm/gems/ruby-2.3.0/wrappers
    gem install thin
    thin -p 8080 start
    rvmsudo thin install
    sudo /usr/sbin/update-rc.d -f thin defaults
    sudo nano /etc/thin/thin.yml
    sudo nano /etc/init.d/thin

# /etc/thin/thin.yml
    port: 8080
    user: ws
    group: ws
    pid: /opt/faye/pids/thin.pid
    timeout: 30
    wait: 30
    log: /opt/faye/log/thin.log
    max_conns: 4096
    require: []
    environment: production
    max_persistent_conns: 1024
    servers: 1
    threaded: true
    no-epoll: true
    daemonize: true
    chdir: /opt/faye
    tag: faye

# bash

# bash
    mkdir /opt/faye/ssl
    openssl req  -nodes -new -x509 -keyout /opt/faye/ssl/server.key -out /opt/faye/ssl/server.cert
    sudo nano /etc/thin/thin.yml

# /etc/thin/thin.yml
    ssl: true
    ssl-key-file: /opt/faye/ssl/server.key
    ssl-cert-file: /opt/faye/ssl/server.cert
    ssl-disable-verify: true

Back within your Rails application you would have the following changes.

# config/secrets.yml

# layouts/application.html.erb
    <%= javascript_include_tag "#{Rails.application.secrets.faye_url}/faye.js" %>
    <%= content_tag :body, data: { faye: Rails.application.secrets.faye_url } do %>
    <% end %>

# assets/javascript/application.js
    $(document).ready(function() {
      var faye_url = $("body").attr('data-faye');
      if (faye_url) {
        var faye = new Faye.Client(faye_url);
        $('.subscribe').each( function(){
         faye.subscribe('/' + $(this).data('channel'), function(data) { return eval(data)});

# helpers/application_helper.rb
    def broadcast_message(channel, content)
      message = { channel: channel, data: content, ext: {auth_token: 'secret'}}
      uri = URI.parse(Rails.application.secrets.faye_url)
      http = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Post.new(uri.request_uri)
      request.set_form_data(message: message.to_json)
      return http.request(request)