最近为了测试热更新,所以需要本地建立一个资源服务器。
使用 WWW www = new WWW(url)来请求服务器assetsbundle资源.
使用C#建立一个http服务
using (var httpListener = new HttpListener())
{
httpListener.Prefixes.Add("http://10.0.4.168:6666/");//监听的路径,最好使用本机固定ip
httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; //匿名访问
httpListener.Start();//开始监听
Console.WriteLine("开始监听 监听的端口:6666");
while (true)
{
//将阻塞线程,直到请求到达
var context = httpListener.GetContext();
//请求到达,取得请求的对象
HttpListenerRequest request = context.Request;
Console.WriteLine("RawUrl:{0}", request.RawUrl);
StreamReader reader = new StreamReader(request.InputStream);
string msg = reader.ReadToEnd();//读取传过来的信息
Console.WriteLine("msg:" + msg);
// 取得回应对象
HttpListenerResponse response = context.Response;
response.ContentEncoding = Encoding.UTF8;
response.ContentType = "text/html; charset=utf-8";
string responseString = string.Format("<HTML>hello,你访问了我</HTML>");
byte[] buff = Encoding.UTF8.GetBytes(responseString);
// 回复
Stream output = response.OutputStream;
output.Write(buff, 0, buff.Length);
// 必须关闭输出流
output.Close();
}
}
unity编辑器模式下使用http://localhost:6688/或http://127.0.0.1:6688/这个是访问一定是没问题的,如下图:
但是为了在模拟器(如雷电)上面进去热更新,所以需要使用电脑固定IP才能访问到。因为模拟器使用127.0.0.1访问的实际上是模拟器本身,(可以想象成模拟器不属于电脑本身)。自己查看和设置自己电脑IP即可
替换自己的ip后。。。。运行上面的代码一定会出错(0……0),因为HttpListener 权限不够拒绝访问。
解决方法:
1、以管理员权限打开CMD命令行
2、使用:netsh http add urlacl url=http://10.0.4.168:6666/ user=Everyone
再次运行代码就不会有这问题啦(O(∩_∩)O)。
如果有问题欢迎给我留言。一起加油吧。