Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
ruanhaishen
Nodemcu Firmware
Commits
1032e9dd
Commit
1032e9dd
authored
Nov 27, 2016
by
Marcel Stör
Browse files
Extract and hoist net receive callbacks
This is done to avoid the accidental upval binding
parent
c54bc05b
Changes
1
Show whitespace changes
Inline
Side-by-side
docs/en/modules/net.md
View file @
1032e9dd
...
...
@@ -135,15 +135,21 @@ Listen on port from IP address.
#### Example
```
lua
-- 30s time out for a inactive client
sv
=
net
.
createServer
(
net
.
TCP
,
30
)
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
sv
:
listen
(
80
,
function
(
c
)
c
:
on
(
"receive"
,
function
(
c
,
pl
)
print
(
pl
)
-- 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
)
c
:
send
(
"hello world"
)
end
)
end
```
#### See also
...
...
@@ -303,8 +309,8 @@ Multiple consecutive `send()` calls aren't guaranteed to work (and often don't)
#### Example
```
lua
srv
=
net
.
createServer
(
net
.
TCP
)
srv
:
listen
(
80
,
function
(
conn
)
conn
:
on
(
"receive"
,
function
(
sck
,
req
)
function
receiver
(
sck
,
data
)
local
response
=
{}
-- if you're sending back HTML over HTTP you'll want something like this instead
...
...
@@ -315,11 +321,11 @@ srv:listen(80, function(conn)
response
[
#
response
+
1
]
=
"e.g. content read from a file"
-- sends and removes the first element from the 'response' table
local
function
send
(
sk
)
local
function
send
(
localSocket
)
if
#
response
>
0
then
sk
:
send
(
table.remove
(
response
,
1
))
then
localSocket
:
send
(
table.remove
(
response
,
1
))
else
sk
:
close
()
localSocket
:
close
()
response
=
nil
end
end
...
...
@@ -328,7 +334,10 @@ srv:listen(80, function(conn)
sck
:
on
(
"sent"
,
send
)
send
(
sck
)
end
)
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:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment