I'm taking a class in the college that require me to create a server-client application, i came up with this code but apparently it has some strange error when I remove the "\n" at the end of the printf(). I already checked with my teacher and it was him who found out that this is was causing my server to freeze and display latter when we send the message, so he put \n in the end of each print(in the beggining there wasn't). We spend a couple of hours trying to find a reason but we didn't find anything to explain, so i'm reaching for you guys(so as my teacher who is curious about), i don't know if we let something pass by.
To create the error that i'm talking about, simply remove \n from each printf and run the code, he'll run but not work properly (even though the port seems to be listen in the telnet command) the lines who was supposed to appear will not show.
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
//criar socket -> bind -> listen -> connection
int socket_name = 0, new_conn = 0;
struct sockaddr_in serv_addr;
char msg_recv[20];
char sendBuff[1025];
socket_name = socket(AF_INET, SOCK_STREAM, 0);
if(socket_name < 0)
{
printf("%s","Failed to create socket, exiting\n");
}else{
printf("%s", "Success\n");
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
bind(socket_name, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(socket_name, 10);
while (1)
{
new_conn = accept(socket_name, (struct sockaddr*)NULL, NULL);
read(new_conn, &msg_recv, sizeof(msg_recv));
printf("New: %s\n", msg_recv);
close(new_conn);
}
return 0;
}
I am testing with nc command, sending a message there, without a client implementation.