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.
6 years ago.
How to implement a socket server properly?
Hello,
I am trying to build a simple socket server using TCPSocket, but my program crashes at some point. What I do is:
init_server_socket( &server_socket, server_port ); // listen on server socket; handle up to MAX_CLIENTS connections server_socket.listen( MAX_CLIENTS ); for(;;) { printf( "Waiting for connection on port %d...\n", server_port ); client = server_socket.accept( &error ); printf( "Got connection, waiting for data...\n" ); n = client->recvfrom( &client_adr, buf, sizeof(buf) ); if( n < 0 ) { printf( "Error %d while receiveing from socket\n", n ); } else { printf( "Received %d chars from %s\n", n, client_adr.get_ip_address() ); client->send( ">", 1 ); client->send( buf, n ); } // need to close the client socket to free resources allocated by socket.accept() printf( "Closing client socket...\n" ); client->close(); <--- crash here printf( "--- socket closed ---\n\n" ); }
The program receives a message and sends it back, that is OK. Then it crashes at client->close() with a stack overflow.
++ MbedOS Error Info ++ Error Status: 0x80020125 Code: 293 Module: 2 Error Message: CMSIS-RTOS error: Stack overflow Location: 0x800F349 File:mbed_rtx_handler>+62 Error Value: 0x1 Current Thread: Id: 0x2000D464 Entry: 0x800F267 StackSize: 0x800F852 StackMem: 0x800F847 SP: 0x2004FF20 For more info, visit: https://armmbed.github.io/mbedos-error/?error=0x80020125 -- MbedOS Error Info --
The documentation says, that the client socket has to be closed after usage, but this does not seem to work... What am I doing wrong?
My platform is the STM disco_f746ng. I am compiling locally using the ARM-GCC.
Many thanks in advance.