Skip to content

Commit

Permalink
Add example for socket:send()
Browse files Browse the repository at this point in the history
Contributes to nodemcu#730
  • Loading branch information
marcelstoer committed Mar 25, 2016
1 parent 280f349 commit 8335a83
Showing 1 changed file with 38 additions and 7 deletions.
45 changes: 38 additions & 7 deletions docs/en/modules/net.md
Expand Up @@ -100,10 +100,10 @@ Listen on port from IP address.
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)
end)
c:send("hello world")
c:on("receive", function(c, pl)
print(pl)
end)
c:send("hello world")
end)
```

Expand Down Expand Up @@ -188,8 +188,8 @@ sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,"192.168.0.66")
sk:on("connection", function(sck,c)
-- Wait for connection before sending.
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
-- Wait for connection before sending.
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
end)
```

Expand All @@ -212,7 +212,38 @@ Sends data to server.

#### Note

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](https://github.com/nodemcu/nodemcu-firmware/issues/730#issuecomment-154241161) for an example and explanation.
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](https://github.com/nodemcu/nodemcu-firmware/issues/730#issuecomment-154241161) for details.

#### Example
```lua
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(sck, req)
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()
if #response > 0
then sck:send(table.remove(response, 1))
else
sck:close()
end
end

-- triggers the send() function again once the first chunk of data was sent
sck:on("sent", send)

send()
end)
end)
```

#### See also
[`net.socket:on()`](#netsocketon)
Expand Down

0 comments on commit 8335a83

Please sign in to comment.