Hello,
I have written a client and server c program, which I have taken from some example code. However, the program run ok, but I can't get anything back from the server. The client should send a single character and the server should increment and then send it back again.
Have I done anything wrong.
Please feel free to point out any bad programming code.
Many thanks for any suggestions,
Steve
My client code below:
Server code:Code:#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int main(int argc, char *argv[]) { printf("This is the client program\n"); int sockfd; int len; struct sockaddr_in address; int result; char ch = 'A'; //Create socket for client. sockfd = socket(AF_INET, SOCK_STREAM, 0); //Name the socket as agreed with server. address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(7734); len = sizeof(address); // result = connect(sockfd, (struct sockaddr *)&address, len); if(result == 1) { perror("Error has occurred"); exit(0); } //Read and write via sockfd write(sockfd, &ch, 1); read(sockfd, &ch, 1); printf("Char from server = %c\n", ch); close(sockfd); exit(0); }
Code:#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int main(int argc, char *argv[]) { //Declaring process variables. int server_sockfd, client_sockfd; int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; //Remove any old socket and create an unnamed socket for the server. server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htons(INADDR_ANY); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *) &server_address, server_len); //Create a connection queue and wait for clients listen(server_sockfd, 5); while(1) { char ch; printf("server waiting\n"); //Accept a connection client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_address, &client_len); //Read write to client on client_sockfd read(client_sockfd, &ch, 1); ch++; write(client_sockfd, &ch, 1); close(client_sockfd); } return 0; }



LinkBack URL
About LinkBacks


