I have hit a weird situation. I am creating a simple echo client-server. The client is able to send message to the server. The accept
call succeeds in the server but for some reason, it does not detect the client message the first time. But when the client sends the message the second time, the server is able to detect the message and print it.
Here is the server snippet where I am accepting the client connection.
while(1) {
// continuously listen for the new client-requests
int client_fd = accept(server_fd, (struct sockaddr*)&client,&client_socklen);
if(client_fd > 0) {
char b[10];
while(1) {
ssize_t response = recv(client_fd,b, 10, 0);
if(response == 0) {printf("reached end of stream"); break;}
if(response == -1) {printf("error"); break;}
}
fprintf("%s", b);
}
}
When the client send the request the first time, the call to accept
succeeds and the control enters the if
block but there it does not receive message and just prints reached end of stream
. But when the client again sends the message, it receives the message and prints it. Why does this happen? Client is sending a simple echo!
message.
Client snippet:
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#define SERVER_ADDR "localhost"
#define SERVER_PORT 8889
int main(int argc, char **argv) {
int socket_fd = 0;
struct sockaddr_in server_socket_addr;
// Converts localhost into 0.0.0.0
struct hostent *he = gethostbyname(SERVER_ADDR);
unsigned long server_addr_nbo = *(unsigned long *)(he->h_addr_list[0]);
// Create socket (IPv4, stream-based, protocol likely set to TCP)
if (0 > (socket_fd = socket(AF_INET, SOCK_STREAM, 0))) {
fprintf(stderr, "client failed to create socket\n");
exit(1);
}
bzero(&server_socket_addr, sizeof(server_socket_addr));
server_socket_addr.sin_family = AF_INET;
server_socket_addr.sin_port = htons(SERVER_PORT);
server_socket_addr.sin_addr.s_addr = server_addr_nbo;
// Connect socket to server
if (0 > connect(socket_fd, (struct sockaddr *)&server_socket_addr, sizeof(server_socket_addr))) {
fprintf(stderr, "client failed to connect to %s:%d!\n", SERVER_ADDR, SERVER_PORT);
close(socket_fd);
// exit(1);
} else {
fprintf(stdout, "client connected to to %s:%d!\n", SERVER_ADDR, SERVER_PORT);
char *my_message = "hey!!"
int bytes_sent = send(socket_fd, my_message, strlen(my_message), 0);
}
// Close the socket and return
close(socket_fd);
return 0;
}