【问题标题】:Buffer Server C缓冲服务器 C
【发布时间】:2017-01-30 14:51:28
【问题描述】:

我一直在用 c 语言尝试这个服务器代码,它第一次正常工作。但是当客户端第二次调用它时,缓冲区仍然保留客户端前一条消息的值,并且第二条消息的值被覆盖在上面。

例如第一条消息是Hello,第二条消息是Hi,缓冲区将是Hillo。我该如何解决?

/*
    C socket server example, handles multiple clients using threads
*/

#include<stdio.h>
#include<string.h>    //strlen
#include<stdlib.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write
#include<pthread.h> //for threading , link with lpthread
 int i;
//the thread function

void *connection_handler(void *);

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c , *new_sock;
    struct sockaddr_in server , client;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8080 );

    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");

    //Listen
    listen(socket_desc , 3);

    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);


    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");

        pthread_t sniffer_thread;
        new_sock = malloc(1);
        *new_sock = client_sock;

        if( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)
        {
            perror("could not create thread");
            return 1;
        }

        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( sniffer_thread , NULL);
        puts("Handler assigned");
    }

    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }

    return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[];



    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , strlen(client_message));


    }

    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }


    //Free the socket pointer
    free(socket_desc);

    return 0;
}

【问题讨论】:

  • new_sock = malloc(1); 应该是 new_sock = malloc(sizeof client_sock);。否则,您将在下一行 *new_sock = client_sock; 陷入未定义的行为。
  • OT:将c 定义为socklen_t,并在对accept() 的调用中删除对socklen_t* 的强制转换。
  • OT:同样recv() 返回ssize_t 不 int。
  • char client_message[]; 没有分配要读取的缓冲区。事实上,它与char *client_message; 相同,这样使用它会引发未定义的行为。请改用char client_message[2000];。

标签: c sockets server buffer


【解决方案1】:

使用memset函数在接收消息前清除缓冲区。

memset(client_message,'\0', sizeof(client_message));

【讨论】:

  • 为什么?只需要观察实际收到的字节数。这种事情只是货物崇拜编程。
【解决方案2】:

不要使用strlen(client_message),使用read_size。这就是你得到的字节数,所以这就是你发送的字节数。

问题是消息末尾没有 NUL 终止符,所以 strlen 不起作用。要将 NUL 终止符放在消息的末尾,请执行以下操作:

client_message[read_size] = '\0';

然后您可以将client_message 与接受字符串的函数一起使用,例如strlen、printf、puts 等。

但是,如果您所做的只是将消息回显给发件人,那么您无需为 NUL 终止符而烦恼。

【讨论】:

    【解决方案3】:
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , strlen(client_message));
    
    
    }
    

    常见错误。您假设 recv() 填充了缓冲区。这是一个回显服务器,因此您应该只回显您实际收到的内容:

    while( (read_size = recv(sock, client_message, sizeof client_message, 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , read_size);
    }
    

    【讨论】:

      【解决方案4】:

      问题在于,strlen() 一直在计数,直到找到一个空字节。

      您收到的第二条消息没有空字节来终止它。因此,strlen() 将返回一个数字“x”,它是下一个空字节的距离。这意味着,您的程序将写入“x”字节而不仅仅是消息。

      要解决此问题,您只需将read_size 传递给write() 函数,或者,如果您想继续使用strlen(),请将client_message[read_size] 设置为'\0'。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-17
        • 2011-08-22
        • 2015-02-16
        • 2015-03-15
        • 1970-01-01
        • 2013-03-02
        • 2015-04-14
        • 2016-08-05
        相关资源
        最近更新 更多