Socket 模块

函数功能:发送 tcp/udp 请求

脚本实例:

local ts = require("ts")
local socket = require("socket")
local host = "www.baidu.com"
local file = "/"
local sock = assert(socket.connect(host, 80))  -- 创建一个 TCP 连接,连接到 HTTP 连接的标准 80 端口上
sock:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
repeat
    local chunk, status, partial = sock:receive(1024) -- 以 1K 的字节块来接收数据,并把接收到字节块输出来
    dialog(chunk or partial, 0)
until status ~= "closed"
sock:close()  -- 关闭 TCP 连接
local ts = require("ts")
local socket = require("socket")
local host = host or "127.0.0.1"
local port = port or 8080
print("Binding to host '" ..host.. "' and port " ..port.. "...")
--创建 udp 对象
udp = assert(socket.udp())
--绑定到指定的端口
assert(udp:setsockname(host, port))
--设置超时时间
assert(udp:settimeout(5))
--获取绑定 IP 和端口
ip, port = udp:getsockname()
assert(ip, port)
print("Waiting packets on " .. ip .. ":" .. port .. "...")
local recvmaxbyte =20
--单线程无限循环
while 1 do
    --接收udp packet
    dgram, ip, port = udp:receivefrom(recvmaxbyte)
    if(dgram=="终止")then
        nlog("终止")
        break
    end
    if dgram then
        nlog("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port)
        --发送数据
        udp:sendto(dgram, ip, port)
    else
        nlog(ip)
    end
end
udp=nil
collectgarbage("collect")
Copyright 北京帮你玩科技有限公司 2020 all right reserved,powered by Gitbook该文章修订时间: 2020-02-02 14:04:44

results matching ""

    No results matching ""