Created
February 25, 2025 22:12
-
-
Save masakk1/0b234340647850e0bc1ab617e8128f20 to your computer and use it in GitHub Desktop.
Code to test the type annotations for LuaCATS/luasocket 's UDP module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local socket = require("socket") | |
local client, err = socket.udp() | |
local server, err = socket.udp() | |
assert(client, err) | |
assert(server, err) | |
---@cast server UDPSocketUnconnected | |
server:setsockname("127.0.0.1", 12345) | |
---@cast client UDPSocketConnected | |
client:setsockname("127.0.0.2", 12345) -- would be "*" and an ephemeral port otherwise. But also works! | |
client:setpeername("127.0.0.1", 12345) | |
-- setting an option | |
local option_success, option_error = server:setoption("ipv6-v6only", true) | |
print(option_success, option_error) -- fails because we're bind it to an IPv4 it beforehand. | |
-- peername | |
local peer_ip, peer_port = client:getpeername() | |
print(peer_ip, peer_port) | |
print(pcall(function() | |
local peer_ip, peer_port = server:getpeername() --errors because its connected only | |
print(peer_ip, peer_port) | |
end)) | |
-- timeout | |
server:settimeout(0) | |
local timeout = server:gettimeout() | |
print(timeout) | |
client:settimeout(42) | |
local timeout = client:gettimeout() | |
print(timeout) | |
-- receivesfrom | |
server:settimeout(0) | |
client:settimeout(0) | |
client:send("hello") | |
local pkt, ip_err, port = server:receivefrom() | |
print(pkt, "from", ip_err, port) --prints hello where from | |
local pkt, ip_err, port = server:receivefrom() | |
print(pkt, ip_err, port) -- prints nil and timeout | |
-- can't use `from` for connected clients. | |
server:sendto("from server to client", "127.0.0.2", 12345) | |
print(pcall(function() | |
local pkt, ip_err, port = client:receivefrom() --error because its unconnected only | |
print(pkt, ip_err, port) | |
end)) | |
--receive | |
-- receive is a function that can be used both by a connected and an unconnected socket. | |
-- works exactly like receivefrom but without the source | |
server:sendto("from server to client", "127.0.0.2", 12345) | |
local pkt, err = client:receive() | |
print(pkt, err) | |
client:send("from client to server") | |
local pkt, err = server:receive() | |
print(pkt, err) | |
-- also has timeouts | |
local pkt, err = client:receive() | |
print(pkt, err) -- timeout | |
local pkt, err = server:receive() | |
print(pkt, err) -- timeout | |
server:close() | |
client:close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment