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
        dialog("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port)
        --发送数据
        udp:sendto(dgram, ip, port)
    else
        dialog(ip)
    end
end
udp=nil
collectgarbage("collect")
Copyright 北京帮你玩科技有限公司 2024 all right reserved,powered by Gitbook该文章修订时间: 2024-10-08 11:38:05

results matching ""

    No results matching ""