4

I have a Sinatra app that uses Websockets.
My app works when I run it with ruby app.rb, but doesn't when I'm trying to run it with shotgun app.rb.

This is in my sending_out.erb:

<script>
$(document).ready(function(){
connection = new WebSocket('ws://' + window.location.host + window.location.pathname);
connection.onopen = function(){
    $("#msgs").append('Connection opened'+"<br>")
};
connection.onmessage = function(e){
    $("#msgs").append(e.data+"<br>");
};
connection.onclose = function() {
    $("#msgs").append('Connection closes from view'+"<br>");
};
$("form").submit(function(){
    connection.send( $("input").val() );
});
});
</script>

And this is in my app.rb:

require 'sinatra-websocket'
set :sockets, []
get '/sending_out' do
request.websocket do |connection|
  connection.onopen do
    connection.send("Hello World!")
    settings.sockets << connection

    connection.send("opened")
    connection.send("went")

  end
  connection.onmessage do |msg|
    EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
  end

  connection.onclose do
    warn("websocket closed")
    settings.sockets.delete(ws)
  end
end
end

It must show

Connection opened
Hello World!
opened
went

when I go to the page. But it only shows

Connection closes from view

with Shotgun.

And in the console it says WebSocket connection to 'ws://127.0.0.1:9393/sending_out' failed: Error during WebSocket handshake: Unexpected response code: 500.

Is there an issue running Websockets with Shotgun?

aronchick
  • 6,786
  • 9
  • 48
  • 75
Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70

1 Answers1

2

The main feature of Shotgun is that it automatically reloads your whole code every request and I think that could be also the problem you are facing.

Shotgun should be used just for development.

For production purposes you have plenty of other options available:

Comparison of ruby servers can be found on https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications

Rene
  • 450
  • 1
  • 7
  • 10
  • I don't know if it will work because I already don't have this code, but in case someone was facing my problem and it got resolved by this answer, please tell me this so I can accept it. – Evgenia Karunus Oct 01 '15 at 02:07