I have a need to send largish amounts of data from a Photon to my computer, and I assumed that using TCP would be the way to go. I modified some code I found on an Arduino site that works fine, but I clearly have some misunderstanding of what a sever and a client are, since I don’t understand why the code works. I thought that it should be the server that would read the incoming URL request (from an OS X app), and the server that would then write out data to the computer. However, in the code below, you can see that it is the client that does all the reading and writing.
TCPServer server = TCPServer(80);
TCPClient client;
byte data[] = {131,260,37,41,152,163,77,18,99,100,214}; // dummy data for a test
void setup() {
// start listening for clients
server.begin();
Serial.begin(9600);
while(!Serial.available()) Particle.process();
Serial.println(WiFi.localIP());
}
void loop() {
// listen for incoming clients
client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println();
for (int i=0; i< sizeof(data)/sizeof(data[0]); i++) {
client.printf("%d ", data[i]);
}
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
delay(100);
client.stop();
Serial.println("client disconnected");
}
}
So why isn’t the server doing the reading and writing? What is the meaning of “client” that’s returned from server.client()? Also, a more general question; is using TCP the best way to send data from a Photon to my computer for data that will be in the 1000 byte range?