如何以编程方式获取 Sinatra 的活动端口?

发布于 2025-01-13 08:59:40 字数 788 浏览 0 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贪恋 2025-01-20 08:59:40

尝试这个

require 'sinatra'
require 'socket'

socket = Socket.new(:INET, :STREAM, 0)
socket.bind(Addrinfo.tcp("127.0.0.1", 0))

port = socket.local_address.ip_port
socket.close

set :port, port
set :bind, "127.0.0.1"

get "/" do
    "Hello, World!"
end

socket.local_address.ip_port 将为您提供端口信息,但您需要在启动 sinatra 之前关闭该套接字,否则它将失败并显示 Errno::EADDRINUSE

Try this

require 'sinatra'
require 'socket'

socket = Socket.new(:INET, :STREAM, 0)
socket.bind(Addrinfo.tcp("127.0.0.1", 0))

port = socket.local_address.ip_port
socket.close

set :port, port
set :bind, "127.0.0.1"

get "/" do
    "Hello, World!"
end

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 with Errno::EADDRINUSE

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文