Bill Hamlin
Bill Hamlin

Reputation: 1

NodeMCU TCP connection timeout

I am trying out the Elecrow ESP8266 and using the NodeMCU firmware (nodemcu_integer_0.9.6-dev_20150704.bin). My connection code looks like this:

function foo()
  conn = net.createConnection(net.TCP, 0)      
  conn:on("connection", function() 
    text = "some text\r\n"
    conn:send(text)
  end)
  conn:connect(5000,"192.168.240.1")
end

This is in a function. My first question is when do we exit out of this function? Do I have to explicitly have an 'exit' statement? I realize NodeMCU is event-driven, and the call to connect is after the logic handling a 'connection' (at which point I send something). I'm ok with that but I wonder how and when we get out of 'foo'.

The other thing is, how do I implement a timeout on this? I'd want to timeout and exit when that occurs.

Thanks for any tips.

Upvotes: 0

Views: 1053

Answers (1)

Mitxel
Mitxel

Reputation: 11

In this piece of code, between function foo() and end, you are defining the function foo () not executing it at this moment.

This code will be executed when this function is called in another code with a foo()

When you call foo () and the foo () code is executed, When you call foo () and the foo () code is executed, you first

conn = net.createConnection(net.TCP, 0)

create (in the present) a socket and assign it to the variable conn. conn is the soket from that moment.

Then,

conn:on("connection", function() 
  text = "some text\r\n"
  conn:send(text)
end)

you assign a callback function that will be executed in the (future) event when the socket achieves a connection.

Then,

conn:connect(5000,"192.168.240.1")

you ask the plug to try a connection and the execution of the function foo () ends (and foo () returns)

In an imaginary time line things could go like this.

When the interpreter reads the code [function foo() ... end], the function foo () is defined, but not executed.

0us foo() The foo() code starts executing because we call foo()

20us net.create... The socket is created

40us conn:on... Certain callback function is asignated to de socket

60us conn:connect.. The socket starts an attempt to connect

65 us The foo() function ends and returns, and "another code" is executed

120 us The socket achieves the connection and the callback function is triggered

125 us The callback code:

text = "some text\r\n"
conn:send(text)

is executed in parallel with "another code"

The future event "socket connected" fires, in the future, the callback asigned, in the present, with conn:on()

Upvotes: 1

Related Questions