C sockets: why is my server appending extra characters in the end?

谁都会走 提交于 2019-12-06 19:45:33

You need a string in order to use strlen(). Your arrays are not strings, rely on read_size instead for the length of the buffer.

Strings in are just a sequence of printable characters followed by a '\0', and none of your arrays has any '\0' so strlen() is causing undefined behavior. The strlen() function actually scans the string until it finds the '\0' and in the process it counts how many characters were there.

Alt Eisen

@Iharob's answer is correct. Basically, change the line:

write(client_socket_fd, buffer, strlen(buffer))

to:

write(client_socket_fd, buffer, read_size)

It isn't. You are printing junk at the end of your buffer. You're also ignoring end of stream.

if(recv(socket_fd, server_reply, BUFSIZE,0)<0) {
    fprintf(stderr,"failed to reply. \n");
    break;
}
fprintf(stdout, "Reply: %s\n ", servreply);

should be

int count;
if((count = recv(socket_fd, server_reply, BUFSIZE,0))<0) {
    fprintf(stderr,"failed to reply. \n");
    break;
}
else if (count == 0) {
    // EOS
    fprintf(stderr, "peer has disconnected.\n");
    break;
} else {  
    fprintf(stdout, "Reply: %.*s\n ", count, servreply);
}

Your 'write back to the client' is also incorrect:

if (0 > write(client_socket_fd, buffer, strlen(buffer))) {

should be

if (0 > write(client_socket_fd, buffer, read_size)) {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!