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!