'Can sinatra listen to more than one port?

I want one running sinatra application to listen on two ports 80 and 4567?

Is that possible

  • on Windows XP
  • using ruby only
  • running only one instance of my sinatra application?


Solution 1:[1]

As far as I know, no it's not - https://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb

Solution 2:[2]

You could launch two different copies of the application, sharing the same database:

ruby myapp.rb -p 80 &
ruby myapp.rb -p 4567 &

These would run in two separate Ruby processes, which may or may not cause a problem (depending on if you are storing any information in the process). However, the default cookie-based sessions even work across processes:

require 'sinatra'

enable :sessions
get '/in/:msg' do
  session[:msg] = params[:msg]
  "I stored #{session[:msg]}"
end

get '/out' do
  "Here you go: #{session[:msg]}"
end

In action:

phrogz$ ruby sessions.rb -p 3000 &
[1] 58698

phrogz$ ruby sessions.rb -p 3001 &
[1] 58699

phrogz$ curl -b cookies.txt -c cookies.txt http://localhost:3000/in/foo
I stored foo

phrogz$ curl -b cookies.txt -c cookies.txt http://localhost:3000/out
Here you go: foo

phrogz$ curl -b cookies.txt -c cookies.txt http://localhost:3001/out
Here you go: foo

Solution 3:[3]

If you are open to using puma to start the application, then you can do something like:

bundle exec puma -b tcp://0.0.0.0:3000 -b tcp://0.0.0.0:4000

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gef
Solution 2 Phrogz
Solution 3 Surya Shanmughan