LuaSocket
Ví dụ: thời gian kết nối bị giới hạn
local socket = require("socket")
local sock = socket.tcp()
sock:settimeout(0.2) -- thiết lập thời gian kết nối bị giới hạn (giây)
if (sock:connect("220.181.57.217", 80)) then
sock:close()
sys.alert("Kết nối thành công")
else
sys.alert("Thời gian kết nối bị giới hạn")
end
Lưu ý: Sử dụng sys.alert
Ví dụ: mô phỏng HTTP GET cho trang chủ Baidu
local socket = require('socket')
local sock = socket.tcp()
local ip = assert(socket.dns.toip('www.baidu.com'), 'Không thể giải quyết DNS')
sock:settimeout(10)
assert(sock:connect(ip, 80) == 1, 'Kết nối thất bại hoặc thời gian kết nối bị giới hạn')
assert(
sock:send(
'GET / HTTP/1.1\r\n'..
'Host: www.baidu.com\r\n'..
'Accept: */*\r\n'..
'Connection: close\r\n'..
'\r\n'
),
'Thời gian gửi bị giới hạn'
)
local buf = {}
repeat
local chunk, status, partial = sock:receive(4096)
if (chunk) then
buf[#buf + 1] = chunk
else
if (partial) then
buf[#buf + 1] = partial
end
end
until status == "closed"
sock:close()
sys.alert(table.concat(buf))
Lưu ý: Sử dụng sys.alert, table.concat