luanet:一个lua的网络库
这套接口是单线程的,通过PeekMsg获取网络事件,PeekMsg会在底层驱动epoll主循环.虽然也可以提供多线程的接口,
在下面启动一个线程来驱动epoll,将事件提交到消息队列,由PeekMsg获取。但是,没人有会指望用lua写一个高性能的
网络服务器,所以决定还是提供一个简单的接口,用来写写简单的小程序就可以了.
首先介绍一下向lua提供的接口:
lua_register(lState,"Connect",&luaConnect); //连接到远程服务器
lua_register(lState,"CloseConnection",&luaCloseConnection); //销毁连接
lua_register(lState,"CreateNet",&luaCreateNet); //创建网络接口
lua_register(lState,"PeekMsg",&luaPeekMsg); //从消息队列提取事件
lua_register(lState,"CreateWpacket",&luaCreateWpacket); //创建一个写包
lua_register(lState,"ReleaseRpacket",&luaReleaseRpacket); //释放一个读包
lua_register(lState,"SendPacket",&luaSendPacket); //发送一个数据包
lua_register(lState,"PacketReadString",&luaPacketReadString);//从数据包中读取字符串
下面看一写用这套接口编写的echo服务器
echo.lua
local registernet = assert(package.loadlib("./luanet.so","RegisterNet")) registernet() function mainloop() local netengine = CreateNet("127.0.0.1",8012) while true do local type,connection,rpacket = PeekMsg(netengine,50) if type then if type == 1 then print("a connection comming") elseif type == 3 then local wpkt = CreateWpacket(rpacket,0) SendPacket(connection,wpkt) local msg = PacketReadString(rpacket) print(msg) ReleaseRpacket(rpacket) elseif type == 2 then print("disconnect") CloseConnection(connection) else end end end end mainloop()
相当简单,首先是导入luanet.so动态库,并调用网络接口注册函数,然后在127.0.0.1的8012端口上创建一个网络引擎.
然后循环调用PeekMsg获取事件即可.
目前还有些小bug需要解决.