Since | Origin / Contributor | Maintainer | Source |
---|---|---|---|
2014-12-22 | Zeroday | PhoeniX | net.c |
** TLS operations was moved to the TLS module **
Constants to be used in other functions: net.TCP
, net.UDP
Creates a client.
net.createConnection([type[, secure]])
type
net.TCP
(default) ornet.UDP
secure
1 for encrypted, 0 for plain (default)
!!! attention
This will change in upcoming releases so that net.createConnection
will always create an unencrypted TCP connection.
There's no such thing as a UDP _connection_ because UDP is connection*less*. Thus no connection `type` parameter should be required. For UDP use [net.createUDPSocket()](#netcreateudpsocket) instead. To create *secure* connections use [tls.createConnection()](tls.md#tlscreateconnection) instead.
- for
net.TCP
- net.socket sub module - for
net.UDP
- net.udpsocket sub module - for
net.TCP
withsecure
- tls.socket sub module
net.createConnection(net.TCP, 0)
net.createServer()
, net.createUDPSocket()
, tls.createConnection()
Creates a server.
net.createServer([type[, timeout]])
type
net.TCP
(default) ornet.UDP
timeout
for a TCP server timeout is 1~28'800 seconds, 30 sec by default (for an inactive client to be disconnected)
!!! attention
The type
parameter will be removed in upcoming releases so that net.createServer
will always create a TCP-based server. For UDP use net.createUDPSocket() instead.
- for
net.TCP
- net.server sub module - for
net.UDP
- net.udpsocket sub module
net.createServer(net.TCP, 30) -- 30s timeout
net.createConnection()
, net.createUDPSocket()
Creates an UDP socket.
net.createUDPSocket()
none
Join multicast group.
net.multicastJoin(if_ip, multicast_ip)
if_ip
string containing the interface ip to join the multicast group. "any" or "" affects all interfaces.multicast_ip
of the group to join
nil
Leave multicast group.
net.multicastLeave(if_ip, multicast_ip)
if_ip
string containing the interface ip to leave the multicast group. "any" or "" affects all interfaces.multicast_ip
of the group to leave
nil
Closes the server.
net.server.close()
none
nil
-- creates a server
sv = net.createServer(net.TCP, 30)
-- closes the server
sv:close()
Listen on port from IP address.
net.server.listen([port],[ip],function(net.socket))
port
port number, can be omitted (random port will be chosen)ip
IP address string, can be omittedfunction(net.socket)
callback function, pass to caller function as param if a connection is created successfully
nil
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
function receiver(sck, data)
print(data)
sck:close()
end
if sv then
sv:listen(80, function(conn)
conn:on("receive", receiver)
conn:send("hello world")
end)
end
Returns server local address/port.
net.server.getaddr()
none
port
, ip
(or nil, nil
if not listening)
Closes socket.
close()
none
nil
Connect to a remote server.
connect(port, ip|domain)
port
port numberip
IP address or domain name string
nil
Provides DNS resolution for a hostname.
dns(domain, function(net.socket, ip))
domain
domain namefunction(net.socket, ip)
callback function. The first parameter is the socket, the second parameter is the IP address as a string.
If a callback c
is provided, it is equivalent to having called :on("dns", c)
on this socket; this callback will, hereafter, receive any pending
resolution results recieved for this socket!
nil
sk = net.createConnection(net.TCP, 0)
sk:dns("www.nodemcu.com", function(conn, ip) print(ip) end)
sk = nil
Retrieve port and ip of remote peer.
getpeer()
none
port
, ip
(or nil, nil
if not connected)
Retrieve local port and ip of socket.
getaddr()
none
port
, ip
(or nil, nil
if not connected)
Throttle data reception by placing a request to block the TCP receive function. This request is not effective immediately, Espressif recommends to call it while reserving 5*1460 bytes of memory.
hold()
none
nil
Register callback functions for specific events.
on(event, function())
event
string, which can be "connection", "reconnection", "disconnection", "receive" or "sent"function(net.socket[, string])
callback function. Can benil
to remove callback.
The first parameter of callback is the socket.
- If event is "receive", the second parameter is the received data as string.
- If event is "disconnection" or "reconnection", the second parameter is error code.
If reconnection event is specified, disconnection receives only "normal close" events.
Otherwise, all connection errors (with normal close) passed to disconnection event.
nil
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
-- Wait for connection before sending.
srv:on("connection", function(sck, c)
-- 'Connection: close' rather than 'Connection: keep-alive' to have server
-- initiate a close of the connection after final response (frees memory
-- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6
sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)
srv:connect(80,"httpbin.org")
!!! note
The receive
event is fired for every network frame! Hence, if the data sent to the device exceeds 1460 bytes (derived from Ethernet frame size) it will fire more than once. There may be other situations where incoming data is split across multiple frames (e.g. HTTP POST with multipart/form-data
). You need to manually buffer the data and find means to determine if all data was received.
local buffer = nil
srv:on("receive", function(sck, c)
if buffer == nil then
buffer = c
else
buffer = buffer .. c
end
end)
-- throttling could be implemented using socket:hold()
-- example: https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/pcm/play_network.lua#L83
Sends data to remote peer.
send(string[, function(sent)])
sck:send(data, fnA)
is functionally equivalent to sck:send(data) sck:on("sent", fnA)
.
string
data in string which will be sent to serverfunction(sent)
callback function for sending string
nil
Multiple consecutive send()
calls aren't guaranteed to work (and often don't) as network requests are treated as separate tasks by the SDK. Instead, subscribe to the "sent" event on the socket and send additional data (or close) in that callback. See #730 for details.
srv = net.createServer(net.TCP)
function receiver(sck, data)
local response = {}
-- if you're sending back HTML over HTTP you'll want something like this instead
-- local response = {"HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n"}
response[#response + 1] = "lots of data"
response[#response + 1] = "even more data"
response[#response + 1] = "e.g. content read from a file"
-- sends and removes the first element from the 'response' table
local function send(localSocket)
if #response > 0 then
localSocket:send(table.remove(response, 1))
else
localSocket:close()
response = nil
end
end
-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)
send(sck)
end
srv:listen(80, function(conn)
conn:on("receive", receiver)
end)
If you do not or can not keep all the data you send back in memory at one time (remember that response
is an aggregation) you may use explicit callbacks instead of building up a table like so:
sck:send(header, function()
local data1 = "some large chunk of dynamically loaded data"
sck:send(data1, function()
local data2 = "even more dynamically loaded data"
sck:send(data2, function(sk)
sk:close()
end)
end)
end)
Changes or retrieves Time-To-Live value on socket.
ttl([ttl])
ttl
(optional) new time-to-live value
current / new ttl value
sk = net.createConnection(net.TCP, 0)
sk:connect(80, '192.168.1.1')
sk:ttl(1) -- restrict frames to single subnet
Unblock TCP receiving data by revocation of a preceding hold()
.
unhold()
none
nil
Remember that in contrast to TCP UDP is connectionless. Therefore, there is a minor but natural mismatch as for TCP/UDP functions in this module. While you would call net.createConnection() for TCP it is net.createUDPSocket() for UDP.
Other points worth noting:
- UDP sockets do not have a connection callback for the
listen
function. - UDP sockets do not have a
connect
function. Remote IP and port thus need to be defined insend()
. - UDP socket's
receive
callback receives port/ip after thedata
argument.
Closes UDP socket.
The syntax and functional identical to net.socket:close()
.
Listen on port from IP address.
The syntax and functional similar to net.server:listen()
, but callback parameter is not provided.
Register callback functions for specific events.
The syntax and functional similar to net.socket:on()
. However, only "receive", "sent" and "dns" are supported events.
!!! note
The receive
callback receives port
and ip
after the data
argument.
Sends data to specific remote peer.
send(port, ip, data)
port
remote socket portip
remote socket IPdata
the payload to send
nil
udpSocket = net.createUDPSocket()
udpSocket:listen(5000)
udpSocket:on("receive", function(s, data, port, ip)
print(string.format("received '%s' from %s:%d", data, ip, port))
s:send(port, ip, "echo: " .. data)
end)
port, ip = udpSocket:getaddr()
print(string.format("local UDP socket address / port: %s:%d", ip, port))
On *nix systems that can then be tested by issuing
echo -n "foo" | nc -w1 -u <device-IP-address> 5000
Provides DNS resolution for a hostname.
The syntax and functional identical to net.socket:dns()
.
Retrieve local port and ip of socket.
The syntax and functional identical to net.socket:getaddr()
.
Changes or retrieves Time-To-Live value on socket.
The syntax and functional identical to net.socket:ttl()
.
Gets the IP address of the DNS server used to resolve hostnames.
net.dns.getdnsserver(dns_index)
dns_index which DNS server to get (range 0~1)
IP address (string) of DNS server
print(net.dns.getdnsserver(0)) -- 208.67.222.222
print(net.dns.getdnsserver(1)) -- nil
net.dns.setdnsserver("8.8.8.8", 0)
net.dns.setdnsserver("192.168.1.252", 1)
print(net.dns.getdnsserver(0)) -- 8.8.8.8
print(net.dns.getdnsserver(1)) -- 192.168.1.252
Resolve a hostname to an IP address. Doesn't require a socket like net.socket.dns()
.
net.dns.resolve(host, function(sk, ip))
host
hostname to resolvefunction(sk, ip)
callback called when the name was resolved.sk
is alwaysnil
There is at most one callback for all net.dns.resolve()
requests at any time;
all resolution results are sent to the most recent callback specified at time
of receipt! If multiple DNS callbacks are needed, associate them with separate
sockets using net.socket:dns()
.
nil
net.dns.resolve("www.google.com", function(sk, ip)
if (ip == nil) then print("DNS fail!") else print(ip) end
end)
Sets the IP of the DNS server used to resolve hostnames. Default: resolver1.opendns.com (208.67.222.222). You can specify up to 2 DNS servers.
net.dns.setdnsserver(dns_ip_addr, dns_index)
dns_ip_addr
IP address of a DNS serverdns_index
which DNS server to set (range 0~1). Hence, it supports max. 2 servers.
nil
This part gone to the TLS module, link kept for backward compatibility.