LWIP Socket API: Accept the same client several times doesn't work
Posted: Wed Apr 25, 2018 3:24 pm
Hello,
I have some problems with the LWIP Socket API for ESP32.
With the function accept() I am waiting for a tcp client to connect to the ESP32 as tcp server. Then I can receive data from the client via recv(). This works as expected.
Now I want to disconnect the client from the server and accept the socket from the same client again. To do this I close the socket and wait again for a client to connect to the server. This only works twice, the third call of accept() results in the return -1. revc() is now always unblocked, although no message is received.
I have no idea what i'm doing wrong. Why i can only accept two clients? Or is there another way to reconnect a client to a server?
I have some problems with the LWIP Socket API for ESP32.
With the function accept() I am waiting for a tcp client to connect to the ESP32 as tcp server. Then I can receive data from the client via recv(). This works as expected.
Now I want to disconnect the client from the server and accept the socket from the same client again. To do this I close the socket and wait again for a client to connect to the server. This only works twice, the third call of accept() results in the return -1. revc() is now always unblocked, although no message is received.
Code: Select all
void tcp_test_task(void *par){
char rec_buffer[128];
char* rec_data;
uint8_t rec_size;
uint8_t client_disconnect = 1;
int32_t res;
const uint16_t server_port = 10;
int32_t tcp_server_socket = 0;
int32_t tcp_client_socket = 0;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
tcp_server_socket = lwip_socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = lwip_htonl(INADDR_ANY);
server_addr.sin_port = htons(server_port);
res = lwip_bind(tcp_server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
res = lwip_listen(tcp_server_socket, 5);
//Up to here there are no errors
while(1){
//Accept new client
tcp_client_socket = lwip_accept(tcp_server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
//After the third call of accept() it returns the error -1
if (tcp_client_socket < 0){
printf("Error in accept(): %d\n", tcp_client_socket);
}
client_disconnect = 1;
while(client_disconnect){
//receive messages from the client
rec_size = lwip_recv(tcp_client_socket, rec_buffer, 128, 0);
if (rec_size == 0) { //client disconnected from server
client_disconnect = 0; //go back to accept()
lwip_close(tcp_client_socket);
} else {
rec_data = malloc((rec_size + 1) * sizeof(char));
strncpy(rec_data, rec_buffer, rec_size);
rec_data[rec_size] = '\0';
if (!strcmp(rec_data, "Disconnect")){
client_disconnect = 0; //go back to accept()
lwip_close(tcp_client_socket);
}
free(rec_data);
}
}
}
}