Reputation: 3423
i am learning socket programming...i was trying to create a program in which i enter a sentence on the client screen and it is transmitted to the server and then it appears on the terminal on which the server is running....the codes are here.....(after seeing the first answer to this question i realised my mistake and changed sockfd1 in read() function to connfd and used fork() after accept() in server.cpp...but still prog doesn't work )
earlier in client.cpp, i had used fgets(clibuff, 100, stdin) and had put this and write(sockcli, clibuff, strlen(clibuff)) in an infinite for loop but that didn't work...
so i decided to make it work for just one statement and removed the for loop....but this too doesn't work...
when i run these on two separate command lines they both start fine(since the x from both the programs output 0)...but when i type anything on client side and press enter...it doesn't appear on server window... The relevant parts of code are:
-------server.cpp-----
int sockfd1;
sockfd1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
int x=bind(sockfd1, (sockaddr*)(&serv), sizeof(serv)); //serv is my sockaddr_in structure
cout<<x<<endl;
listen(sockfd1,5);
listen(sockfd1,5);
int y;
for(;;)
{
connfd=accept(sockfd1, &cliaddr, &siz);
if((y=read(sockfd1, servbuff, 100))>0) //i changed sockfd1 here to connfd
fputs(servbuff, stdout);
}
-----client.cpp------
char clibuff[100];
char line[100];
sockaddr_in cli;
bzero(&cli, sizeof(cli));
cli.sin_family=AF_INET;
inet_aton("127.0.0.1", &(cli.sin_addr));
cli.sin_port=htons(2289);
int sockcli;
sockcli=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int x= connect(sockcli,(sockaddr*)&cli, sizeof(cli));
cout<<x<<endl;
cin>>clibuff;
write(sockcli, clibuff, strlen(clibuff));
return 0;
what am i doing wrong?
Upvotes: 2
Views: 227
Reputation: 24897
You are reading from the listening socket. You should not be doing that.
'connfd' is the server<>client socket for the newly-connected client - it is the socket on which you should be reading/writing fo that client. It's common to create a new thread with the 'connfd' as a parameter so that each client can be handled independently.
Read up on accept().
Upvotes: 2