如何以编程方式获取 Sinatra 的活动端口?
我正在 Ruby 上使用 Sinatra 创建一个简单且可移植的 Web 应用程序,并且让系统为服务器找到一个开放端口以用于以下操作:
require 'sinatra'
require 'socket'
socket = Socket.new(:INET, :STREAM, 0)
socket.bind(Addrinfo.tcp("127.0.0.1", 0))
port = socket.local_address.to_s.chomp("\x0").to_i
set :port, port
set :bind, "127.0.0.1"
get "/" do
"Hello, World!"
end
我想启动浏览器以自动查看该应用程序,但是问题是 port
变量和 Sinatra 的 settings.port
都设置为 0
,所以我无法获取服务器的 URL 。
启动代码位于get "/" do
块之后:
Thread.new do
system "chromium-browser " <<
"-app='http://127.0.0.1:#{port}' " <<
"--no-sandbox > /dev/null 2>&1"
end
系统启动后,我可以在WEBrick输出中看到端口,但是如何获取系统预先分配给套接字的端口?
I'm creating a simple and portable web application with Sinatra on Ruby, and I'm letting the system find an open port for the server to use with the following:
require 'sinatra'
require 'socket'
socket = Socket.new(:INET, :STREAM, 0)
socket.bind(Addrinfo.tcp("127.0.0.1", 0))
port = socket.local_address.to_s.chomp("\x0").to_i
set :port, port
set :bind, "127.0.0.1"
get "/" do
"Hello, World!"
end
I'd like to launch the browser to view the application automatically, but the problem is that both the port
variable and Sinatra's settings.port
are set to 0
, so I can't get the URL of the server.
The launch code comes after get "/" do
block:
Thread.new do
system "chromium-browser " <<
"-app='http://127.0.0.1:#{port}' " <<
"--no-sandbox > /dev/null 2>&1"
end
After the system starts, I can see the port in the WEBrick output, but how can I get the port that the system assigns to the socket beforehand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个
socket.local_address.ip_port
将为您提供端口信息,但您需要在启动 sinatra 之前关闭该套接字,否则它将失败并显示Errno::EADDRINUSE
Try this
socket.local_address.ip_port
would give you the port info, but you need to close that socket before starting sinatra or it will fail withErrno::EADDRINUSE