Reputation: 2190
I am trying to write a set of simple client/sever programs that make use of the poll()
system call. Although my code compiles perfectly, while running the program, the client as well as the server display no output. Furthermore, the client keeps on taking input and never stops.
Here is the server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct pollfd fdarray[5];
int sfd, port, nsfd, n, clen, ret, i;
char str[100];
struct sockaddr_in sadd, cadd;
memset(str, 0, sizeof(str));
if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Unable to create socke\n");
exit(1);
}
memset(&sadd, 0, sizeof(sadd));
//port = atoi(argv[1]);
sadd.sin_port = htons(9796);
sadd.sin_family = AF_INET;
sadd.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(sfd, (struct sockaddr *) &sadd, sizeof(sadd)) < 0) {
perror("Error binding to the socket\n");
exit(1);
}
listen(sfd, 5);
clen = sizeof(cadd);
for (i = 0; i < 5; i++) {
nsfd = accept(sfd, (struct sockaddr *) &cadd, &clen);
if (nsfd < 0) {
perror("Error accepting client\n");
exit(1);
}
fdarray[i].fd = nsfd;
fdarray[i].events = POLLIN;
fdarray[i].revents = 0;
}
ret = poll(fdarray,5,10);
for( i = 0; i < 5; i++) {
if (fdarray[i].revents ==POLLIN) {
n = read(fdarray[i].fd,str,100);
if (n < 0)
printf("error reading \n");
printf("message is : %s \n", str);
n = write(fdarray[i].fd, "message received...",
20);
}
}
return 0;
}
Here is the client code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <unistd.h>
#define MAXCOUNT 1024
int main(int argc, char* argv[])
{
int sfd,i;
char msg[MAXCOUNT];
char blanmsg[MAXCOUNT];
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
sfd = socket(AF_INET,SOCK_STREAM,0);
saddr.sin_family = AF_INET;
inet_pton(AF_INET,"127.0.0.1",&saddr.sin_addr);
saddr.sin_port = htons(9796);
connect(sfd,(struct sockaddr*) &saddr, sizeof(saddr));
for(i = 0; i < 5; i++) {
memset(msg,0,MAXCOUNT);
memset(blanmsg,0,MAXCOUNT);
fgets(msg,MAXCOUNT,stdin);
send(sfd,msg,strlen(msg),0);
recv(sfd,blanmsg,sizeof(blanmsg),0);
printf("%s",blanmsg);
fflush(stdout);
}
exit(0);
}
It would be really helpful if you can help me find out what is causing this behavior and how to stop this and run the program correctly.
Upvotes: 1
Views: 2677
Reputation: 27552
I don't know if you realize it but your server basically does nothing until it accepts 5 client connections.
for (i = 0; i < 5; i++) { nsfd = accept(sfd, (struct sockaddr *) & cadd, &clen); if (nsfd < 0) { perror("Error accepting client\n"); exit(1); } fdarray[i].fd = nsfd; fdarray[i].events = POLLIN; fdarray[i].revents = 0; }
Upvotes: 2