Page 1 of 1

Tcp socket closed detection

Posted: Thu Jun 20, 2019 11:05 pm
by rfleming
I have created a TCP client over wifi with the ESP and it connects to my TCP Server on my windows pc just fine. I can do data transmissions, send and receive. Though if I close the server connection I don't get any notification nor can I find a way to poll for if the socket is still active. The only details around this was I found within the arduino API.

This is how I send and receive data atm. I started trying out the errno method like with POSIX C, but regardless of state, it is always 11. Whether the server was opened or closed.

Code: Select all

if (wifiState.wifiConnected && !wifiState.socketConnected) {
	// Create the socket for communication to the client
	if (connectToSocket(&wifiState, (char*)"10.0.0.7")) {
		char str[] = "Hello world\n";
		send(wifiState.clientSocket, (void *)str, strlen(str), 0);
		wifiState.socketConnected = true;
	}
	else {
		wifiState.socketConnected = false;
		puts("wifiState.socketConnected = disconnected");
	}
}

if (wifiState.wifiConnected && wifiState.socketConnected) {
	char buf[256];
	int bytes_received = recv(wifiState.clientSocket, buf, 10, MSG_DONTWAIT);

	if (bytes_received > 0) {
		buf[bytes_received] = 0;	//null safety
		printf("socket read: %s\n", buf);
	}
	else if (bytes_received < 0) {
		//error found...socket closed?
		printf("return %d. errno %d\n", bytes_received, errno);
//				wifiState.socketConnected = false;
	}
}

Re: Tcp socket closed detection

Posted: Tue Jun 25, 2019 6:50 am
by rfleming
Found the solution. if the bytes returned is == 0, the socket has closed. -1 means not bytes received and > 0 is the actual count. Interesting that 0 and -1 are like they are, I thought they would've swapped.


solution:

Code: Select all

char buf[256];
int bytes_received = recv(wifiState.clientSocket, buf, 10, MSG_DONTWAIT);

//bytes_received is 0 on connection close and errno gets set to ENOTCONN (128)
//bytes_received is -1 when no data is received and errno is set to EAGAIN (11)
//bytes_received is > 0 when data is received and errno is set to EAGAIN (11) still.

if (bytes_received > 0) {
	buf[bytes_received] = 0;	//null safety
	printf("socket read: %s\n", buf);
	//close(wifiState.clientSocket);
	//printf("return %d. errno %d\n", bytes_received, errno);
}
else if (bytes_received == 0) {
	//error found...socket closed?
	printf("return %d. errno %d\n", bytes_received, errno);
	wifiState.closeSocket = true;
	//wifiState.socketConnected = false;
}

Re: Tcp socket closed detection

Posted: Tue Jun 25, 2019 12:06 pm
by mikemoy
Just and FYI. if you change MSG_DONTWAIT to 0 you will get what your expecting.

// bytes_received >0, data is present
// bytes_received =0, no data received but connection is still active
// bytes_received =-1 client closed connection
int bytes_received = recv(wifiState.clientSocket, buf, 10, 0);

https://github.com/nkolban/esp32-snippe ... t_server.c