问题描述
我在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