c++ - C sockets: Echo server bad reply -
i've read many questions i've found, still have problem....
i have sample client/server socket:
- connection stablished between server , client done
- receive message client done
- print message in server side done
- send message server client problems
- print server reply in client side problems
i send message client server without problems, when send message i'm allways getting weird characters
note: i'm adding '\0' character received string
client code
//... socket initialization , other code write(sockfd, msg, strlen(msg)); printf("message sent ! \n"); // listen reply listen(sockfd, 5); struct_size = sizeof(con_addr); serverfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size); // read message bytes_read = read(serverfd, server_reply, 100); server_reply[bytes_read] = '\0'; printf("server response: %s \n", server_reply); // close socket close(sockfd); close(serverfd); printf("socket closed ! \n");
server code
//... socket initialization, bind , other code struct_size = sizeof(con_addr); if( (clientfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size)) < 0 ){ perror("could not accept connection. error: "); return 1; } // read message bytes_read = read(clientfd, client_message, 100); client_message[bytes_read] = '\0'; printf("message received: %s \n", client_message); // send message n = write(clientfd, client_message , strlen(client_message));
i'm getting things this:
server response: �v��i�8�y� server response: ��ƿi�8�{�
you confused on how tcp sockets work:
- servers call
socket(2)
,bind(2)
,listen(2)
,accept(2)
setup listening socket. - clients call
socket(2)
,connect(2)
connect server. - once server returns
accept(2)
have bi-directional byte pipe between client , server.
it looks attempting connect/accept on both sides.
other notes:
- always check return values of system calls -
-1
indication of error, inspecterrno(3)
actual problem (strerror(3)
useful here). - do not assume data ascii, not use
strlen(3)
on socket input, use return value ofread(2)
.
Comments
Post a Comment