在C中编写聊天室。获取重复的消息

时间:2017-04-09 17:21:09

标签: c

出于某种原因,当我在聊天室中输入一条长消息后跟一条较短的消息时。我最终收到了较短的消息,然后是下一行上一条消息中的剩余字符。在服务器窗口中,它声明它正在接收搞砸的消息,因此我认为问题出在我的客户端代码中,可能在我的writing_messages线程中。有什么问题?

//CLIENT CODE for writing and reading messages:

void* writing_messages(void* arg) 
{
    char    unfinished_message[2028];
    char    new_msg[2048];
    while(fgets(unfinished_message, sizeof(unfinished_message), stdin))
    {
        strcat(new_msg, arg);    //My arg is a user_name I enter in the cmdline
        strcat(new_msg,": ");
        strcat(new_msg, unfinished_message);
        write(SD, new_msg, strlen(new_msg));
        strcpy(new_msg, "");
        strcpy(unfinished_message, "");
    }
}
void* reading_messages(void* arg) 
{
    char    got_message[2048];
    while(1)
    {
        read(SD, got_message, sizeof(got_message));
        printf("%s\n", got_message);
    }
}
//SERVER CODE for receiving messages

void *
client_session_thread(void * arg)
{
    int     SD;
    char    request[2048];
    char    message[2048] = "server receives input: ";

    SD = *(int *)arg;
    free (arg);
    pthread_detach(pthread_self());
    while (read(SD, request, sizeof(request)))
    {
        strcat(message, request);
        strcat(message,"\n");
        fprintf(stdout, message);
        write(SD,request,strlen(request));
        strcpy(request,"");
        strcpy(message, "server receives input: ");
    }
    close(SD);
    return 0;
}

0 个答案:

没有答案