c - Understanding Client-Server connection -
i'm new socket programming , i'm trying make server-client connection using gcc compiler in linux. server , client ,both codes in different c files.i'm sending character server through user input , server increments character , return client.the client should remain in connection until character 'q' user.i'm having trouble in maintaining connection. here i'm pasting client code.it works fine when don't use while loop , sends 1 character if repeatedly want send character on same connection , , connection close when user enters q. well, in 1st iteration of loop asks character , gets incremented character server 2nd time says "transport endpoint connected". kindly me in understanding this.
int main(int argc, char *argv[]) { int sockfd; int len, port; struct sockaddr_in address; int result; char ch; port = atoi(argv[1]); sockfd = socket(af_inet, sock_stream, 0); address.sin_family = af_inet; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = port; len = sizeof(address); while (1){ printf("enter character send server or q/q end connection:"); scanf("%c", &ch); fflush(stdin); if (connect(sockfd, (struct sockaddr *)&address, len) == -1) { perror("oops: client failed connect"); return 1; } if (ch == 'q' || ch == 'q'){ printf("connection closed"); break; } write(sockfd, &ch, 1); read(sockfd, &ch, 1); printf("incremented character server = %c\n", ch); } close(sockfd); return 0; }
it's hard tell might going wrong without posting subsequent edits.
maybe closing file descriptor accidentally due placement of brackets (as part of while loop block definition)?
you should need call connect() once in case. following code works fine me (my server code writes character received client , client receives/prints expected).
i had add:
address.sin_port = htons(port); then move connect() function call out of while loop ensuring close function call made when breaking loop i.e. receiving q or q.
int main(int argc, char *argv[]) { int sockfd; int len, port; struct sockaddr_in address; int result; char ch; port = atoi(argv[1]); sockfd = socket(af_inet, sock_stream, 0); address.sin_family = af_inet; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(port); len = sizeof(address); if (connect(sockfd, (struct sockaddr *)&address, len) == -1) { perror("oops: client failed connect"); return 1; } while(1) { printf("enter character send server or q/q end connection:"); scanf("%c", &ch); fflush(stdin); if (ch == 'q' || ch == 'q'){ printf("connection closed"); break; } write(sockfd, &ch, 1); read(sockfd, &ch, 1); printf("incremented character server = %c\n", ch); } close(sockfd); return 0; } if still having problems, maybe strange happening within server code. accidentally disconnecting client?
some great, easy understand examples here:
Comments
Post a Comment