My TCP client seems to have a race condition with my server!
Hello people
I have been trying to make an educational TCP server-client model in c++, using the standard c socket libraries.
for full reference and a GitHub - stefmitropoulos/simple_c_tcp_client: Simple TCP Client in c++c-make file, you can visit the code for the server here and for the client here GitHub - stefmitropoulos/simplesocketserver: Simple C++ socket server.
I am using spdlog library for logging, used less than 10 times though. If you don't want to download it from GitHub - gabime/spdlog: Fast C++ logging library. just remove it in the code
What I have done is:
Server Side :
Create a socket, bind, listen to it and accept when there is a pending connection. After that, spawn a thread to handle the connection and detach it.
The thread sends a welcome message to the client, receives a message from the client and returns the message with the Caesar Cipher applied to it.
Client Side :
Create a socket and connect to the server. Receive the message and then send a message to the server. Then receive the ciphered text.
My problem lies (I think) in the client side.
Code:
char buff[MAX];
if (recv(sockfd, buff, sizeof(buff), 0) < 0)
{
exit(6);
}
puts(buff);
bzero(buff, sizeof(buff));
strcpy(buff, "PIZZA");
if (send(sockfd, buff, sizeof(buff), 0) < 0) {
exit(5);
}
struct pollfd fds[1];
fds[0].fd = sockfd;
fds[0].events = (POLLIN);
int ret = 1;
while (ret) {
ret = poll(fds, 1, 2000);
if (ret == -1) {
spdlog::error("ERROR ON POLL");
exit(5);
}
if (ret == 0) {
spdlog::info("Timeout reached");
}
while (ret) {
if (fds[0].revents == 0) {
continue;
}
ret--;
if (fds[0].revents & POLLIN) { //NOLINT
//INCOMING DATA
bzero(buff, sizeof(buff));
if (recv(sockfd, buff, 100, MSG_DONTWAIT) < 0) {
puts("Recv()");
exit(6);
}
}
}
}
close(sockfd);
std::cout << "Reply from the server: " << buff << std::endl;
I am writing the buffer with 0s before receiving a final time, but when ran, this part prints nothing!
When I run it on the debugger, or if I induce a sleep() just before the recv(), I get \nQJAAB, the caesar cipher version of PIZZA!
It is driving me mad, any help would be appreciated!