Websocket connection closes without opening on Shotgun server

243 Views Asked by At

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?

1

There are 1 best solutions below

1
Rene On

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