Hello;
I am writing this TCPClient which will multiplex between the stdin and socket to get mesages from the server. The server is implemented to deal with multiple clients. But I have written the following code. But when I run the code, it is only going in the infinite loop and not even printing the statements which I have mentioned below. And obviously, it is not working as I want to work (send messages and receive messages at the same time)
I see in the following thread that there has been a discussion on this. But I am still having problemCode:/* tcpclient.c */ #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> int main() { int sock, bytes_recieved; char send_data[1024],recv_data[1024]; struct hostent *host; struct sockaddr_in server_addr; fd_set read_fds; char ch; int count = 0; int i; host = gethostbyname("127.0.0.1"); //create the socket if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } //set server info server_addr.sin_family = AF_INET; server_addr.sin_port = htons(5000); server_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(server_addr.sin_zero),8); //connect to the server if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Connect"); exit(1); } printf("stage 1"); //the program is not even printing this but it is going to the infinite loop below!!!! while(1) { //initialize the readset and add stdin and the socket to it FD_ZERO(&read_fds); FD_SET(0, &read_fds); FD_SET(sock, &read_fds); printf("Send something: %s",send_data); //this is also is not getting printed if(select(sock+1, &read_fds, NULL, NULL, NULL) == -1) { perror("Server-select() error lol!"); exit(1); } if(FD_ISSET(0, &read_fds)) //something has happened in the stdin { printf("key pressed"); //when I press a key, it should get here, but its not printing this also!! ch = getc(0); if (ch=='\n') //user typed enter, time to send the content of the buffer and clear it { send(sock, send_data, sizeof(send_data), 0); send_data[0]='\0'; count = 0; } else //append the pressed character to the buffer { printf("here"); //it is also not printed!!! send_data[count]=ch; count++; } } else if(FD_ISSET(sock, &read_fds)) //server has sent something { bytes_recieved = recv(i, recv_data, sizeof(recv_data), 0); printf("%s",recv_data); recv_data[0]='\0'; } }//end of infinite while return 0; }
Multiplexing read socket and stdin
Thanks for your help;
Arnamoy



LinkBack URL
About LinkBacks


