In my socket programming, i am to read input from a user on the client side on a loop until the user inputs an empty string, send it to server and have the server search through a text file to find something that matches the input from user.
I dont know what but something is wrong with the loop on the client side. Its a do while loop. It reads in once and gives the appropriate result(that even has a glitch) but then when the user gives an input a second time, it hangs. It does not send what the user just inputted to the server. It just hangs. CLIENT program:
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
//char buffer[256];
if (argc < 1) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
char str1[300]= " ";
printf("Enter server port number: ");
scanf("%s", str1);
portno = atoi(str1);
//create a socket point
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
exit(1);
}
char str[300]= " ";
printf("Enter server host name: ");
scanf("%s", str);
server = gethostbyname(str);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
//now connect to server
if (connect(sockfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{
error("ERROR connecting");
exit(1);
}
//NOW ASK FOR MESSAGE FROM USER, read by server
char buffer[256];
char buffer2[256];
do //**i believe problem starts here**
{
printf("Enter a college major: ");
bzero(buffer,256);
scanf("%s", buffer);
//send message to server
n = write(sockfd,buffer,strlen(buffer));
if (n < 0) {
error("ERROR writing to socket");
exit(1);
}
//now read server response
bzero(buffer,256);
n = read(sockfd,buffer,256);
if (n < 0)
{
error("ERROR reading from socket");
exit(1);
}
printf("%s\n",buffer);
} while(strcmp(buffer, " "));
return 0;
printf("Hello 1\n");
}
the input(College major) the user might put could have spaces, so the "scanf("%s", buffer);" does not work for those. This is what i meant by glitch. If someone puts in "Computer Science" only "Computer" is sent to the server. I am compiling this in linux so gets(buffer) is not allowed. I dont know what to do. Also is there a way to write this do-while loop as just a while loop. I want to terminate the program when the user inputs an empty string.