Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 6 months ago.
Reconnection of a disconnected tcp client
Hello,
I'm running a tcp server on my controller. I'm using the ethernetinterface and the tcpserver library. Every things ok, just only: If the client disconnects, I can't start the listen methode again. It returns all time a timeout. Only if I'm closing and restarting (bind) the server, the listen methode will get a new connection. Any ideas, what's wrong?
Thanks for help, Joachim
1 Answer
11 years, 6 months ago.
*************** HTTP Server Task //
- include "main.h"
- include "Server.h"
extern PROGRM *prg; extern EthernetInterface eth; char netrxbfr[NETBFRSZ]; char nettxbfr[NETBFRSZ];
void Server(const void *arg) { REQUEST request; int bytcnt; int retsts;
printf("HTTP Server started\r\n");
TCPSocketServer server; Create new socket if(server.bind(HTTP_SERVER_PORT) < 0 ) Bind port to socket { printf("sock.bind() has failed\r\n"); server.close(); eth.disconnect(); osThreadTerminate(prg->srvThreadId); return; ?????? }
if(server.listen(1) < 0 ) Listen for connect request { printf("sock.listen() has failed\r\n"); server.close(); eth.disconnect(); osThreadTerminate(prg->srvThreadId); return; ??????? }
while(TRUE) Server restart loop { TCPSocketConnection sock; Get a socket for client connection while(server.accept(sock) < 0); Wait for a connect request printf("Connection accepted from %s\r\n", sock.get_address());
In the following loop read data from HTTP Client and parse it
while(TRUE) Server Message processing loop { if((bytcnt = sock.receive(netrxbfr, NETBFRSZ)) <= 0) { printf("sock.recv() has timed out\r\n"); sock.close(); break; } netrxbfr[bytcnt] = '\0';
if(ParseRequest(netrxbfr, bytcnt, &request) == FALSE) { printf("Server:ParseRequest() Invalid HTTP Request\r\n"); sock.close(); break; }
switch(request.reqType) Dispatch type of request(Get, Post, ...) { case tGet: retsts = ProcessGetRequest(&sock, &request); break; case tPost: retsts = ProcessPostRequest(&sock, &request); break; case tHead: default: HTMLSendNotImplemented(&sock); retsts = FALSE; break; }End switch
if(retsts == FALSE || request.dispos == FALSE) { printf("Server() Invalid HTTP Request, closing socket\r\n"); sock.close(); break;
} } end while printf("Socket closed\r\n"); } end while loop }
I had the same problem in the past. Do not call bind and listen in the server loop; Simply close the socket, this will destroy theTCPSocketConnection object. In the loop recreate the TCPSocketConnection object and wait for connection.
Hope this helps, Guenter.