首页 > 解决方案 > Julia:如何让 HTTP.jl 从 WSL2 VM 的 ip 服务?

问题描述

我在 WSL2 上启动了一个简单的 http 服务器,以在 localhost:8081 提供简单的 HTML 页面。

我想通过主机上的 localhost:8081 (或任何 URL)访问它。

我按照说明https://docs.microsoft.com/en-us/windows/wsl/compare-versions

我曾经ip addr | grep eth0在inet下找到IP,然后我用Python和Julia启动了一个简单的HTTP服务器

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

上面的 python 版本可以正常工作,但 Julia 服务器无法正常工作。

using HTTP
using HTTP: Sockets, @ip_str
HTTP.serve() do request::HTTP.Request
   @show request
   @show request.method
   @show HTTP.header(request, "Content-Type")
   @show HTTP.payload(request)
   try
       return HTTP.Response("Hello")
   catch e
       return HTTP.Response(404, "Error: $e")
   end
end

它为 HTTP 流量打开端口 8000 和 8081。然后我去了主机并做localhost:8081$WSL2VMIP:8081

都没有奏效。

标签: httpjuliawsl-2

解决方案


对于 Julia,您似乎需要提供 WSL2 VM 的 IP。使用获取 IPip addr | grep eth0并查找类似 IP172.69.13.20/20并设置myip = ip"172.69.13.20"

请注意,使用ip"0.0.0.0"很方便,但可能不安全(例如在公共咖啡馆),因此请小心使用。

using HTTP
using HTTP: @ip_str
HTTP.serve(myip) do request::HTTP.Request
   @show request
   @show request.method
   @show HTTP.header(request, "Content-Type")
   @show HTTP.payload(request)
   try
       return HTTP.Response("Hello")
   catch e
       return HTTP.Response(404, "Error: $e")
   end
end

推荐阅读