I have a few question regarding mbed OS 5's new TCP API:
Some background:
I will have multiple mbeds linked via Ethernet to a PC. The PC, whose IP address is fixed and known by each mbed, initiates the connections (mbeds effectively acting as servers).
The mbed only needs to handle one socket at a time, and the PC should have no problem reconnecting (thereby opening a socket on the mbed) to the mbed, should the connection fail at any point, or the socket is closed by the PC (i.e. the mbed should happily accept and open a socket if there is no open socket).
Question
My proposed approach would be to call accept() on the listener socket, storing the result in a temporary buffer. If the result is NULL (no socket to be accepted), continue. If result is not NULL (we have a pointer to a new socket), close the current socket, and point it to the address returned by accept. All of this, as well as the send() and recv() calls would occur in a while(true) loop.
By accept() returning a new socket, it is assumed that the host (PC) initiated a new connection due to the previous one (which the mbed has no way of telling is now lost) being lost/closed. Therefore, it should be no problem discarding the current socket and replacing it with the new one
Does this seem like a sensible approach?
EDIT:
I've come up with an example of what I was describing above. Hasn't been tested, but should still convey the idea.
#include "mbed.h"
#include "EthernetInterface.h"
// Network interface
EthernetInterface net;
TCPSocket listener;
TCPSocket* client;
// Socket demo
int main()
{
int remaining;
int rcount;
char *p;
char *buffer = new char[256];
nsapi_size_or_error_t result;
net.set_network("192,168,0,101","192,168,0,101","192,168,0,101");
net.connect();
listener.open(&net);
listener.bind(80);
listener.listen(1);
client = listener.accept(NULL);
client->set_timeout(1000);
while(1) {
int remaining = 256;
int rcount = 0;
p = buffer;
while (remaining > 0 && 0 < (result = client->recv(buffer, remaining))) {
p += result;
rcount += result;
remaining -= result;
}
if (result == 0) { //Peer has shutdown connection
client->close(); //close socket;
client = listener.accept(NULL); //block again until new connection comes through
client->set_timeout(1000);
}
if (result == NSAPI_ERROR_TIMEOUT ) { //Assume connection has been lost
client->close(); //close socket;
client = listener.accept(NULL); //block again until new connection comes through
client->set_timeout(1000);
}
}
}
Best Answer
Why not use UDP in this case? There won't be any socket opening, you can just listen on a socket on the Mbed board and computers can send data to the port. No problem with abandoning sockets.
Note that we have an example of a multi-threaded HTTP 1.1 webserver here: http-webserver-example if you need some inspiration on building TCP servers on top of Mbed OS.