Reputation: 10553
I've read as many questions as I've found, still I have my problem....
I have a very sample client/server socket:
I send the message from client to server without problems, but when I send back the message I'm allways getting weird characters
Note: I'm adding the '\0' character to the received string
//... socket initialization and other code
write(sockfd, msg, strlen(msg));
printf("Message sent ! \n");
// Listen for 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");
//... socket initialization, bind and 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 back
n = write(clientfd, client_message , strlen(client_message));
I'm getting things like this:
Server response: �V��i�8�y�
Server response: ��ƿi�8�{�
Upvotes: 2
Views: 592
Reputation: 84159
You are confused on how TCP sockets work:
socket(2)
, bind(2)
, listen(2)
, accept(2)
to setup its listening socket.socket(2)
and then connect(2)
to connect to a server.accept(2)
you have a bi-directional byte pipe between client and the server.It looks like currently you are attempting to connect/accept on both sides.
Other notes:
-1
is an indication of an error, then inspect errno(3)
for the actual problem (strerror(3)
is useful here).strlen(3)
on socket input, use return value of read(2)
.Upvotes: 4