C套接字:为什么我的服务器最后添加额外的字符? [英] C sockets: why is my server appending extra characters in the end?

查看:44
本文介绍了C套接字:为什么我的服务器最后添加额外的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C编写一个简单的服务器/客户端套接字。客户端要求用户输入消息,服务器通过重复相同的消息进行响应。问题是,当我从客户端发送消息时,服务器通过附加额外的字符进行响应。我该如何解决。

I am writing a simple server/client socket in C. The client asks the user to input a message and the server responds by repeating the same. The problem is when I send a message from the client the server responds back by appending extra character. How do I fix this.

这是我的客户代码

while(1) {
    bzero(buffer, BUFSIZE);
    printf("Enter Message: ");
    scanf("%s", buffer);
    //send some data
    if(send(socket_fd, buffer, strlen(buffer), 0) <0) {
        fprintf(stderr,"sending failed\n");
        return 1;
    }
//receive a reply from the server
if(recv(socket_fd, server_reply, BUFSIZE,0)<0)
{
    fprintf(stderr,"failed to reply. \n");
    break;
}
fprintf(stdout, "Reply: %s\n ", servreply);

}

这是我的服务器代码

 int read_size;
    while((read_size = recv(client_socket_fd, buffer, BUFSIZE,0))>0)
    {

        // Reply back to the client
        if (0 > write(client_socket_fd, buffer, strlen(buffer))) {
            fprintf(stderr, "could not write back to socket\n");
        } else {
            fprintf(stdout, "message back to client\n");
        }
    }
    if(read_size==0)
    {
        fprintf(stderr,"disconnected.\n");
        fflush(stdout);
    }
    else if(read_size==-1){
        fprintf(stderr, "error.\n");
    }

这是输出

 Enter Message: welcome
Reply: welcome
 Enter Message: hello
Reply: hellome
 Enter Message: hi
Reply: hillome


推荐答案

您需要一个 string 以便使用 strlen()。您的数组不是字符串,而是依靠 read_size 代替缓冲区的长度。

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.

的问题只是一系列可打印字符,后跟'\0',并且您的数组都没有任何'\0',因此 strlen( )导致未定义的行为。 strlen()函数实际上扫描 string ,直到找到'\0',并在此过程中计算出其中有多少个字符。

Strings in c 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.

这篇关于C套接字:为什么我的服务器最后添加额外的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆