I have two peers: Alice and Bob. Bob is trying to send Alice the list of peers known to him.
First, Bob tells Alice how many peers he has, then he sends n
strings with the information about peers to Alice.
Here's the code for Bob:
if ((send(socket_fd, &(int){ 1 }, sizeof(int), 0)) == -1) { perror("Failed to send"); }
sleep(1); // Give him time to process the rqst
send(socket_fd, &peer_cnt, sizeof(peer_cnt), 0);
for (int i = 0; i < peer_cnt; ++i) {
char *peer_str = get_string(&peers[i]);
printf("Send peer\t:\t%s\n", peer_str);
send(socket_fd, peer_str, strlen(peer_str), 0);
free(peer_str);
}
Here's the code for Alice:
char buf[128] = { 0 };
int n = 0;
recv(peer_sock_fd, &n, sizeof(n), 0);
printf("Number of incoming peers:\t%d\n", n);
for (int i = 0; i < n; ++i) {
memset(buf, '\0', sizeof(buf));
recv(peer_sock_fd, buf, sizeof(buf), 0);
puts(buf);
}
Example. If Bob sends Alice 2
strings, then there are two cases exist.
First, Alice gets them separately (as it's intended by me), e.g. Alice's output might be in this case george:127.0.0.1:5555:
and michael:127.0.0.1:4444:
.
Second, Alice gets them as single string, like this george:127.0.0.1:5555:michael:127.0.0.1:4444:
Why are incoming strings merged sometimes?