I have been tweaking around with tcp code of making client server model. The client will send the name and department where he/she works and server will respond with time at which the input was performed and also the server will write the data from client into a text file. But when i run the code, it sometimes write okay and sometimes mix up the characters from buffer. If anyone can guide, where i have been making mistake, it be great! Here is below the code for client.c and server.c:
client.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<string.h>
#define MAX 200
#include <netinet/in.h>
int main() {
char request[256] = "Hello I am Client are you there";
char buf[MAX];
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(3001);
connect(sock, (struct sockaddr *) &server_address, sizeof(server_address));
int i,n;
for (i=0;i<10;i++)
{
printf("TIME IN : ");
n = 0;
while ((buf[n++] = getchar()) != '\n')
;
write(sock, buf, sizeof(buf));
if ((strncmp(buf, "exit", 4)) == 0) {
printf("Client exiting...\n");
break;
}
read(sock, buf, sizeof(buf));
if ((strncmp(buf, "exit", 4)) == 0) {
printf("Client exiting...\n");
break;
}
printf("From Server : %s \n", buf);
}
close(sock);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
server.c
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include<time.h>
#include <netinet/in.h>
#define MAX 200
int main() {
FILE *fptr;
fptr = fopen("program.txt", "w");
char server_message[256] = "Hi, Yes you have reached the server!";
char buf[MAX];
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(3001);
server_address.sin_addr.s_addr = INADDR_ANY;
bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));
listen(server_socket, 5);
int client_socket;
client_socket = accept(server_socket, NULL, NULL);
int n;
for (n=0;n<10;n++) {
bzero(buf,MAX);
read(client_socket, buf, sizeof(buf));
if (strncmp("exit", buf, 4) == 0) {
printf("Server Exit...\n");
break;
}
printf("Time Sequence: %s\t", buf);
fprintf(fptr,"%s", buf);
bzero(buf,MAX);
time_t current_time = time(NULL);
struct tm *tm = localtime(¤t_time);
strftime(buf, sizeof(buf), "%c", tm);
write(client_socket, buf, sizeof(buf));
if (strncmp("exit", buf, 4) == 0) {
printf("Server exiting...\n");
break;
}
}
fclose(fptr);
close(server_socket);
return 0;
}
What I have tried:
i have tried to empty the buffer variable but so far no results!