16行代码能做什么?写一个随机图片服务器!

在经过一番旷日持久的苦战后,自己的开源游戏引擎 EtherEngine 终于迎来了 4.x 版本
更新内容
本次更新除了增加了更多系统交互 API,优化了接口调用方式和二进制数据传参缓冲区之外,更重要的是对 Network 模块 进行了十分重要的更新,让 EtherEngine 的网络模块摇身一变变成了可以与 Python 的 Requests 库 / Nodejs 的 Express 框架 功能相媲美的工具了!

EtherEngine 虽然被更名为了 EtherAPI ,但是我更习惯叫它原来的名字(因为这样更装x),它的设计思想是尽可能地简单、易上手并且易于快速开发,所以这次网络模块的更新也恰恰印证了它的这些特性:

16行代码能够做点啥?
—— 写一个随机图片服务器足够!

上代码!

首先引用相关的模块:

1
2
OS = UsingModule("OS")
Network = UsingModule("Network")

然后创建我们的服务端:

1
server = Network.CreateServer()

接下来定义变量储存路径以及图片列表,并配置路由响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- 定义图片资源目录
image_dir = "./image"
-- 遍历目录获取当前图片目录下的文件名
file_list = OS.ListDirectory(image_dir)
-- 配置默认的路由请求:返回图片
server:Get("/", function(req, res)
local file_name = file_list[math.random(#file_list)]
local image_file = io.open(OS.JoinPath(image_dir, file_name), "rb")
res:SetContent(image_file:read("*a"), "image/png")
image_file:close()
end)
-- 配置 update 路由:热更新图片文件列表
server:Get("/update", function(req, res)
file_list = OS.ListDirectory(image_dir)
res:SetContent("update image file list success")
end)

最后,只需要让我们的服务器监听端口就可以了:

1
server:Listen("localhost", 8080)

双击 EtherEngine.exe 运行服务器,打开浏览器输入对应网址就可以看到随机返回的图片了:
测试截图
全部的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OS = UsingModule("OS")
Network = UsingModule("Network")

server = Network.CreateServer()
-- 定义图片资源目录
image_dir = "./image"
-- 遍历目录获取当前图片目录下的文件名
file_list = OS.ListDirectory(image_dir)
-- 配置默认的路由请求:返回图片
server:Get("/", function(req, res)
local file_name = file_list[math.random(#file_list)]
local image_file = io.open(OS.JoinPath(image_dir, file_name), "rb")
res:SetContent(image_file:read("*a"), "image/png")
image_file:close()
end)
-- 配置 update 路由:热更新图片文件列表
server:Get("/update", function(req, res)
file_list = OS.ListDirectory(image_dir)
res:SetContent("update image file list success")
end)

server:Listen("localhost", 8080)

使用过 Express 框架的小伙伴可能就有很熟悉的感觉了~

关于网络模块 Client 相关的操作,下次再发文介绍吧,后续可能会写文章剖析引擎的源代码,感兴趣的朋友可以关注一下,为项目的 GitHub 点一颗星,或者在评论区留言~

项目链接:https://github.com/VoidmatrixHeathcliff/EtherEngine

作者

Voidmatrix

发布于

2021-05-13

更新于

2024-05-13

许可协议

评论