当前位置:首页 > CN2资讯 > 正文内容

LUA语言上传服务器 lua服务器开发

18小时前CN2资讯

    因为最近的项目需要,学习了lua编程,并使用lua进行网络相关的开发,在此记录一下用到的相关的知识。

    在整个项目中,我只是负责其中的固件升级模块的开发,数据格式是自定义的,并没有采用Json或者是XML,主要是因为传输的字段比较少,而且不希望引入太多的第三方库。

一、LuaSocket

    项目中,采用的是tcp通信,这里仅介绍tcp相关的知识。

    1.首先需要加载socket模块:

local socket = require('socket')

    如果要查看LuaSocket的版本:

print('LuaSocket ver: ', socket._VERSION)

    2. tcp常用方法:

关于以下方法的说明,我觉得官方文档已经说得很清楚了,在此就直接引用官方说明:

socket.bind(address, port [, backlog])

    创建一个tcp server object bind to (address, port), backlog是用于listen函数的。熟悉Linux下的socket编程,会觉得这些都很熟悉的。此函数返回一个tcp server object,如果失败返回nil。

server:accept() Waits for a remote connection on the server object and returns a client object representing that connection. client:getsockname() : 获取socket的ip与port 4)server:getpeername() : 获取对端的ip与port client:receive([pattern [, prefix]]) 接收数据,pattern与lua file I/O format类似,取值有: reads from the socket until the connection is closed. No end-of-line translation is performed; reads a line of text from the socket. The line is terminated by a LF character (ASCII 10), optionally preceded by a CR character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern. This is the default pattern; causes the method to read a specified number of bytes from the socket. If successful, the method returns the received pattern. In case of error, the method returns nil followed by an error message which can be the string 'closed' in case the connection was closed before the transmission was completed or the string 'timeout' in case there was a timeout during the operation. Also, after the error message, the function returns the partial result of the transmission. client:send(data [, i [, j]]) Sends data through client object. is the string to be sent. The optional arguments i and j work exactly like the standard string.sub Lua function to allow the selection of a substring to be sent. If successful, the method returns the index of the last byte within [i, j] that has been sent. In case of error, the method returns nil, followed by an error message,followed by the index of the last byte within [i, j] that has been sent. client:close() : Closes a TCP object. 8)master:settimeout(value [, mode]) Changes the timeout values for the object. By default, all I/O operations are blocking. server:setoption(option [, value]) Sets options for the TCP object. Options are only needed by low-level or time-critical applications. 如我们常用的:'keepalive', 'reuseaddr', 'tcp-nodelay'

master:connect(address, port) : 用于户客户端发起连接请求

    下面的代码分别展示了tcp服务端与客户端的大致结构:

-- echo server local socket = require('socket') local serv = socket.bind('*', 8000) -- bind to any ip and 8000 port. if not serv then print('bind error') os.exit(-1) end while true do print('begin accept') local client = serv:accept() if not client then print('accept failed') os.exit(-1) end local peer_ip, peer_port = client:getpeername() print(string.format('handle %s:%d request begin', peer_ip, peer_port)) while true do local data, err = client:receive('*line') -- read one line data if not err then print('data: ', data) client:send(data) -- send data back to client else print('err: ', err) break end end client:close() end-- echo client local socket = require('socket') local client = socket.connect('localhost', 8000) -- connect to localhost:8000 if not client then print('connect failed') os.exit(-1) end while true do local data = io.read('*line') if not data then print('EOF') break end client:send(data) local resp, err, partial = client:receive() if not err then print('receive: ', resp) else print('err: ', err) break end end client:close()


二、Lua bit operation module

    lua语言自身并没有提供位运算,要进行位运算,需要引入第三方module.

local bit = require('bit')

y = bit.band(x1 [,x2...]) : 按位与

 y = bit.bor(x1 [,x2...]) : 按位或

 y = bit.bxor(x1 [,x2...]) : 按位异或

 y = bit.bnot(x) : 按位取反

 y = bit.lshift(x, n) : 逻辑左移

 y = bit.rshift(x, n) : 逻辑右移

 y = bit.arshift(x, n) : 算术右移

    因为我在项目中需要传递整数,需要把整数的低位在前,高位在后进行传输,所以需要用到移位运算。

三、 string模块使用到的一些方法

    因为项目中的数据格式采用的是自定义的,为了解决tcp的粘包问题,所以会存在一个固定大小的头。比如我们的头是:

uin8_t head[4] ; head[0] = 0xA5; // head frame head[1] = 0x1l; // cmd_id uint16_t len = 0x0010; head[2] = len & 0xff; // low byte of len head[3] = len >> 8; // hight byte of len uin8_t head[4] ; head[0] = 0xA5; // head frame head[1] = 0x1l; // cmd_id uint16_t len = 0x0010; head[2] = len & 0xff; // low byte of len head[3] = len >> 8; // hight byte of len

    那么在Lua中,我们要怎么才能做到把上述的4个字节头发送出去呢?可以用如下的方法:string.char()

local len = 0x0010 local t = {0xA5, 0x1, bit.band(len, 0xff), bit.rshift(len, 8)} local data = string.char(unpack(t)) client:send(data)

    那么接收方,在收取到数据头时,需要怎么去解析呢? string.byte()

local req , err = client:receive(4) if not err then local req_t = {string.byte(req, 1, -1)} local frame = req_t[1] local cmd_id = req_t[2] local len = req_t[3] + bit.lshift(req_t[4], 8) print(string.format('frame:%02x, cmd_id:%02x, len:%d', frame, cmd_id, len)) else print('err: ', err) client:close() end


PS : 关于Lua编程的学习,可以参考《lua程序设计》这本书,还有一个博客lua step by step,内容也是根据此书写的,写的非常的好,

    今天先记录到此,后续如有需要再补充。

    

    你可能想看:

    扫描二维码推送至手机访问。

    版权声明:本文由皇冠云发布,如需转载请注明出处。

    本文链接:https://www.idchg.com/info/23826.html

    分享给朋友:

    “LUA语言上传服务器 lua服务器开发” 的相关文章

    GMO VPS:可靠的虚拟专用服务器选择与性能分析

    在我对虚拟专用服务器(VPS)解决方案的探索中,GMO VPS引起了我的注意。作为日本GMO集团旗下的品牌,GMO VPS以其出色的性能和可靠性赢得了众多用户的信赖。我想分享一下为何这个平台如此受欢迎,以及它的相关背景和适用人群。 GMO VPS是如何运作的呢?它使用先进的虚拟技术,将物理服务器划分...

    选择最佳印度尼西亚 VPS 服务商的终极指南

    在了解印度尼西亚的虚拟专用服务器(VPS)之前,我们先来讲讲VPS的基本概念。简单来说,VPS是一种将一台物理服务器划分为多个虚拟服务器的技术。每个虚拟服务器都有独立的操作系统、资源和配置,让用户可以像使用独立服务器一样,获得更高的灵活性和控制权。这种方式不但能满足各种规模的业务需求,还能显著降低成...

    如何选择合适的VPS进行购买:关键因素解析

    选择合适的VPS进行购买是一项涉及多个因素的决策。VPS,即虚拟专用服务器,是一种介于共享主机和独立服务器之间的托管解决方案。特别适合需要灵活性和可扩展性的用户,无论是个人开发者、企业还是网站管理员。这种灵活性让VPS成为现代网络环境中一个非常受欢迎的选择。 VPS与传统的共享主机存在显著区别。传统...

    AMD EPYC 7002处理器:高性能与高能效的完美结合

    我一直对AMD EPYC 7002系列处理器充满兴趣。这款处理器是AMD公司最新推出的服务器处理器,确实让人感到兴奋。基于现代的Zen 2架构,这款处理器融合了先进的7nm制程工艺,投放市场后便以其高性能和高能效著称。随着数据中心和云计算需求的不断增加,EPYC 7002系列成了一个热议的话题,来看...

    银联卡购买:便捷与安全的消费体验

    在这个快速发展的支付时代,银联卡作为一种便捷的支付工具,已经逐渐渗透到我们的日常生活中。我常常发现自己在购物、旅行时,银联卡都能为我省去不少麻烦。通过这张小小的卡片,我可以轻松实现线上和线下消费,四处都能找到它的身影。 银联卡的发展背景十分丰富。自1994年银联成立以来,它不断扩大和完善自己的支付网...

    ROG主机性能评测与游戏体验分析

    ROG(Republic of Gamers)是华硕旗下专注于游戏硬件及相关产品的品牌。这个名称已经成为游戏玩家心目中的一种象征。ROG致力于为玩家提供顶尖的性能和卓越的用户体验,涵盖了从游戏主机到显示器、耳机等全系列的产品。ROG的产品不仅在技术上不断创新,还在设计上追求独特,吸引了众多游戏爱好者...