-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket-ffi.lua
More file actions
46 lines (44 loc) · 1.07 KB
/
socket-ffi.lua
File metadata and controls
46 lines (44 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
local loop = require 'uv-ffi'
local function normalize(options)
local t = type(options)
if t == 'string' then
options = {path = options}
elseif t == 'number' then
options = {port = options}
elseif t ~= 'table' then
assert('Net options must be table, string, or number')
end
if options.port or options.host then
options.isTcp = true
options.host = options.host or '127.0.0.1'
assert(options.port, 'options.port is required for tcp connections')
elseif options.path then
options.isTcp = false
else
error('Must set either options.path or options.port')
end
return options
end
return function(options)
local socket
options = normalize(options)
if options.isTcp then
local res =
assert(
loop:getaddrinfo(
options.host,
options.port,
{
socktype = options.socktype,
family = options.family
}
)[1]
)
socket = loop:newTcp()
socket:connect(res.addr, res.port)
else
socket = loop:newPipe(false)
socket:connect(options.path)
end
return socket
end