LuaSocket 是 Lua 的网络模块库,它可以很方便地提供 TCP、UDP、DNS、FTP、HTTP、SMTP、MIME 等多种网络协议的访问操作。

注意事项:

如何安装

在触动精灵 iOS v2.1.9 及以上版本中包含的苏泽扩展库中已经集成了 luasocket,无需额外下载安装。

httpGet 请求

函数用例

local sz = require("sz")
local http = require("szocket.http")
local res, code = http.request("http://www.baidu.com");
if code == 200 then
    dialog(res,0);
end
--也可以这样
local response_body = {}  
local res, code = http.request({  
  url = "http://www.baidu.com",  
  sink = ltn12.sink.table(response_body)  
})
--获取外网 IP 地址
local sz = require("sz")
local http = require("szocket.http")
local res, code = http.request("http://www.ip.cn/");
--如果此网址无反应,请尝试替换为 http://1212.ip138.com/ic.asp 或其他网址
if code == 200 then
    local i,j = string.find(res, "%d+%.%d+%.%d+%.%d+")
    local ipaddr =string.sub(res,i,j)
    dialog(ipaddr,0)
end

注意事项

  • 返回的 2 个参数中,res 是 http body 的内容,也就是请求网页的内容,code 是 http 状态码, 返回 200 的话就表示正常返回。

  • 如果传入的是 table 的话,就需要用一个容器来接收 http body 的内容。

httpPost 请求

函数用例

local sz = require("sz")--此代码仅为举例说明,请勿直接复制使用。
local http = require("szocket.http")
local response_body = {}
local post_data = 'asd';  
res, code = http.request{  
    url = "http://127.0.0.1/post.php",  
    method = "POST",  
    headers =   
    {  
        ["Content-Type"] = "application/x-www-form-urlencoded",  
        ["Content-Length"] = #post_data,  
    },  
    source = ltn12.source.string('data=' .. post_data),  
    sink = ltn12.sink.table(response_body)  
}

注意事项

  • 这里注意记得 method 传入 POST, 因为默认是 GET。

  • headers 参数,由一个 table 组成,key 为 header,value 为 header 内容。

  • source 参数,这里是填入 POST 的参数,多个数据的情况用 & 隔开,例如 "data1=a&data2=b"。

  • 此代码仅为举例说明,请勿直接复制使用。

挂载代理

函数用例

--必须加上 http:// 否则不处理
local sz = require("sz")
local http = require("szocket.http")
http.PROXY = "http://127.0.0.1:8888" --代理服务器地址
local result = http.request("http://www.baidu.com")
dialog(result,0)

以 socket 的方式访问

函数用例

local sz = require("sz")
local http = require("szocket.http")
local host = "www.baidu.com"
local file = "/"
--创建一个 TCP 连接,连接到 HTTP 连接的标准 80 端口上
local sock = assert(socket.connect(host, 80)) 
sock:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
repeat
    --以 1K 的字节块接收数据
    local chunk, status, partial = sock:receive(1024) 
until status ~= "closed"
-- 关闭 TCP 连接
sock:close()

smtp 方法发送 mail

函数用例

local sz = require("sz")
local smtp = require("szocket.smtp")

from = "<youmail@126.com>" -- 发件人

--发送列表
rcpt = {
    "<youmail@126.com>",
    "<youmail@qq.com>",
    "<youmail@gmail.com>",
}
mesgt = {
    headers = {
        to = "youmail@gmail.com", -- 收件人
        cc = '<youmail@gmail.com>', -- 抄送
        subject = "This is Mail Title"
    },
    body = "这里放邮件内容"
}
r, e = smtp.send{
    server = "smtp.126.com", -- smtp 服务器地址
    user = "youmail@126.com",-- smtp 验证用户名
    password = "******",     -- smtp 验证密码  
    from = from,
    rcpt = rcpt,
    source = smtp.message(mesgt)
}

if not r then
    dialog(e,0)
else
    dialog("发送成功!",0)
end

实现获取网络时间

函数用例

local sz = require("sz")
local socket = require "szocket.core"

server_ip = {
    "132.163.4.101",
    "132.163.4.102",
    "132.163.4.103",
    "128.138.140.44",
    "192.43.244.18",
    "131.107.1.10",
    "66.243.43.21",
    "216.200.93.8",
    "208.184.49.9",
    "207.126.98.204",
    "207.200.81.113",
    "205.188.185.33"
}
function nstol(str)
    assert(str and #str == 4)
    local t = {str:byte(1,-1)}
    local n = 0
    for k = 1, #t do
        n= n*256 + t[k]
    end
    return n
end
function gettime(ip)
    local tcp = socket.tcp()
    tcp:settimeout(10)
    tcp:connect(ip, 37)
    success, time = pcall(nstol, tcp:receive(4))
    tcp:close()
    return success and time or nil
end
function nettime()
    for _, ip in pairs(server_ip) do
        time = gettime(ip)
        if time then 
            return time
        end
    end
end
dialog(nettime(),0)

统计毫秒精度的时间

脚本示例

local sz = require("sz")
local socket = require ("szocket")
function sleep(sec)
    socket.select(nil,nil,sec);
end
local t0 = socket.gettime()
sleep(0.4);
local t1 = socket.gettime()
dialog(t1 - t0,0)

生成随机数

函数用例

  1. 设置随机种子

    --设置随机种子
    local sz = require("sz")
    local socket = require("szocket") -- 需要用到 luasocket 库  
    local function get_seed()  
     local t = string.format("%f", socket.gettime())
     local st = string.sub(t, string.find(t, "%.") + 1, -1) 
     return tonumber(string.reverse(st))
    end  
    math.randomseed(get_seed()) 
    for var = 1,5 do
     nLog(math.random())
    end
    
  2. 随机字符串

    --随机字符串
    function randomStr(str, num)
     local ret =''
     for i = 1, num do
         local rchr = math.random(1, string.len(str))
         ret = ret .. string.sub(str, rchr, rchr)
     end
     return ret
    end
    for var = 1,5 do
     s = randomStr("abcdefghijklmnopqrstuvwxyz", 6) --生成 6 位随机字母
     nLog(s)
    end
    
  3. 随机大小写

    --随机大小写
    function rndLetter(num)
     local ret = ""
     pcall(function()
         for var = 1,num do
             if math.random()>0.5 then
                 ret = ret..string.char(math.random(65,90))
             else
                 ret = ret..string.char(math.random(97,122))
             end
         end
     end)
     return ret
    end
    math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6))) --设置随机种子
    for var = 1,5 do
     nLog(rndLetter(10)) --生成一个 10 位随机大小写字母的字符串
    end
    
Copyright 北京帮你玩科技有限公司 2023 all right reserved,powered by Gitbook该文章修订时间: 2024-03-06 17:50:18

results matching ""

    No results matching ""