Http服务器-第十步加入基于Mono平台的C#脚本支持
时间: 2020-06-25来源:OSCHINA
前景提要
该篇是Http服务器系列博文的第十篇。对应项目是LiteHttp具体可访问 http://dreamyouxi.com/litehttp.html 。
Unity引擎中C#脚本运行环境是Mono平台,而非微软的net,Unity引擎大部分是c++编写。
在LiteHttp项目中,原本支持lua脚本支持书写动态网页,这里引入C#脚本来进行辅助c++端开发。
把C#当叫脚本来使用的话,优势比lua多很多,底层还是基于C++构建。

step1:去mono官网下载 msi,x64 x86对于是64和32位exe。
step2:编写C#和c++测试代码
c++:

c#:

cpp运行结果:

在LiteHttpSvr的初步应用:文件系统。把原本C++端的文件读和缓存迁徙到C#实现。
C++端的修改

C#端 using System; using System.Collections.Generic; using System.IO; namespace LiteHttpScript { class CppEntry { static string CallMain(string file) { try { //System.Console.WriteLine("[C# Handle]:" + file); return FileCache.Handle(file); } catch (Exception e) { System.Console.WriteLine("Err:" + e.Message); return ""; } } } public class FileCache { static FileCacheImpl impl = new FileCacheImpl(); public static string Handle(string file) { lock (impl) { return impl.GetFile(file); } } }; //sample LRU file cache which limited by memory public class FileCacheImpl { class FileData { public string key; public string data; public DateTime lastModifyUTCTime; } public string GetFile(string file) { LinkedListNode<FileData> ret = null; if (_cache.TryGetValue(file, out ret)) { //has find cache _list.Remove(ret); _list.AddFirst(ret); //check file will update or not } else { //missing cache try { var data = new FileData(); var info = new FileInfo(file); data.lastModifyUTCTime = info.LastWriteTimeUtc; data.data = File.ReadAllText(file); data.key = file; ret = new LinkedListNode<FileData>(data); _list.AddFirst(ret); _cache.Add(file, ret); _currentMemoryUseage += data.data.Length; } catch (Exception e) { //file not exist return ""; } } while (_list.Count > 1 && _currentMemoryUseage >= MaxMenmoryCacheSize) { var tail = _list.Last; _cache.Remove(tail.Value.Value.key); _list.RemoveLast(); _currentMemoryUseage -= tail.Value.Value.data.Length; } //GC.Collect(); return ret.Value.data; } // private long MaxMenmoryCacheSize { get { return 104857600L; } }//最大缓存大小 100 MB private long MaxMenmoryCacheSize { get { return 100L; } }//最大缓存大小 100 MB // private long MaxCacheFileNum { get { return 1024; } }//最大文件缓存数量 private long _currentMemoryUseage = 0; private Dictionary<string, LinkedListNode<FileData>> _cache = new Dictionary<string, LinkedListNode<FileData>>(); private LinkedList<LinkedListNode<FileData>> _list = new LinkedList<LinkedListNode<FileData>>(); }; }
输出结果:


关于脚本语言的一些其他可以有的特性比如 热更新,C#一样可以有。

科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行