0

I have created a server and client in C using TCP.
Everything works with this simple read and write method (same used for server and client).

buf is global variable in server and client.

Good read()

void read_from(int socket) {
    int readlen;
    if ((readlen = read(socket, buf, sizeof buf - 1)) < 0) {
        perror("read");
    }
    buf[readlen - 1] = '\0';
}

Good write()

void write_to(int socket) {
    if (write(socket, buf, sizeof buf - 1) < 0) {
        perror("write");
    }
}

I want to ensure everything is written, but I can't get it to work.
Using the same read method, this fails:

Bad write()

void write_to(int socket) {
    int buflen = strlen(buf);
    int written, offset = 0;

    while (offset <= buflen) {
        if ((written = write(socket, buf + offset, buflen - offset + 1)) < 0) {
            perror("write");
        }
        fprintf(stderr, "%d\n", written);
        offset += written;
    }
}

The output for fprintf(stderr, "%d\n", written); is correct, so the bad write() seems to write all the same bytes, but the receiver only reads a random half of the lines I send.

Any help is highly appreciated!

  • 2
    You are using a streaming socket, so you can't assume that `read` reads all the information sent by `write` at once. You need to have a message marker so you know when you've received a single `write_to` message. – MicroVirus Nov 22 '15 at 20:24
  • Repeat after me: *TCP is a **stream** protocol, not a **message** protocol*. – Jonathon Reinhart Nov 22 '15 at 20:25
  • I'd think there would be canonical question/answer for these type of questions, but I can't find it. – MicroVirus Nov 22 '15 at 20:27

0 Answers0