How to structure a TCP Client on setup()

I'm working a project that does two TCP connections. Each time the core turns on I need it to get some data from a webpage using TCP and store data recieved in a variable. I've tought that this first TCP connection should be in the setup()(only is executed once) but I don't know how to structure it because, from what I've seen , reading data needs a loop, doesn't it? How could I structure this TCP connection?

The second TCP connection should repeat every X seconds and I think it should be in the loop() part. For this second TCP connection I've followed @BDub TCPClient code on his github and works perfect. TCP CLIENT JSON PARSE EXAMPLE · GitHub

As @BDub, @mtnscott and @weakset mentioned in the topic below, sometimes appear strange characters in the TCP recieved data, but that could be solved adding 'Connection: close' in the header of the http request.

The point is that these solution only works for not chunked http requests. Is there a way to delete his strange characters in a chunked http request?

Thanks guys!

I guess data is usually read in loop, so that setup() won’t take too long and hit the time limit of cloud connection. If you want to that in loop(), you can split the loop with simple variable (pseudo code):

loop() {
  if(startup_phase == true){
    //do the first connection stuff
    //when done, flip the variable
    startup_phase = false;
  } else {
    //do the regular once X second stuff
  }
}

Those strange characters tells you how big chunk you are getting next, so in low level like Spark is, there is no magic way to delete them. (Unless someone writes a library to parse it.)

1 Like

@lia Please check out my updated version of that code here: https://github.com/technobly/SparkCore-FacebookLikesAlert

1 Like