Code:
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#define MAXLINE 4096 /*max text line length*/
#define SERV_PORT 3000 /*port*/
FILE *pF_temperature = NULL;
FILE *pF_light = NULL;
FILE *pF_humidity = NULL;
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
char sendline[MAXLINE], recvline[MAXLINE];
char line1[MAXLINE];
char line2[MAXLINE];
char line3[MAXLINE];
//basic check of the arguments
//additional checks can be inserted
if (argc != 5) {
perror("Usage: TCPClient <IP address of the server");
exit(1);
}
//Create a socket for the client
//If sockfd<0 there was an error in the creation of the socket
if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
perror("Problem in creating the socket");
exit(2);
}
//Creation of the socket
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr= inet_addr(argv[1]);
servaddr.sin_port = htons(SERV_PORT); //convert to big-endian order
//Connection of the client to the socket
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr))<0) {
perror("Problem in connecting to the server");
exit(3);
}
pF_temperature = fopen(argv[2], "r");
pF_light = fopen(argv[3], "r");
pF_humidity = fopen(argv[4], "r");
if ((pF_temperature == NULL) || (pF_light == NULL) || (pF_humidity == NULL))
{
perror("Error: Can not open the three files!");
return -1;
}
/*while (fgets(sendline, MAXLINE, stdin) != NULL) { */
while ((fgets(line1, MAXLINE, pF_temperature) != NULL) &&
(fgets(line2, MAXLINE, pF_light) != NULL) &&
(fgets(line3, MAXLINE, pF_humidity) != NULL))
{
line1[strcspn(line1, "\r\n")] = 0; //remove newline
line2[strcspn(line2, "\r\n")] = 0; //remove newline
line3[strcspn(line3, "\r\n")] = 0; //remove newline
strcat(sendline, "TEMPERATURE = ");
strcat(sendline, line1);
strcat(sendline, "\tLIGHT = ");
strcat(sendline, line2);
strcat(sendline, "\tHUMIDITY = ");
strcat(sendline, line3);
strcat(sendline, "\n"); //add extra newline for one row
send(sockfd, sendline, strlen(sendline), 0);
if (recv(sockfd, recvline, MAXLINE, 0) == 0){
//error: server terminated prematurely
perror("the server terminated prematurely");
exit(4);
}
printf("%s\n", "String received from the server: ");
fputs(recvline, stdout);
}
exit(0);
}