朱莉娅:如何使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

会打开端口8000和8081进行HTTP通信。然后我去了主机,做了localhost:8081$WSL2VMIP:8081

都没有。

解决方法

对于Julia,您似乎需要提供WSL2 VM的IP。使用ip addr | grep eth0获取IP,然后像172.69.13.20/20一样查找IP并设置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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...