-1

我在 C 中有两个程序:
一个客户端和一个服务器。

我不打算开发代码的所有细节,一切正常。除了这一点:我希望我的服务器发送彩色确认消息并让我的客户端识别它们。

在服务器上,这些行如下所示:

    //server side there there is:
    FILE * stream; // for the socket

    fprintf(stream,"\x1b[31m220\x1B[0m GET command received please type the file name\n");
    //here stream refers to a classic BSD socket which connect client to server
    //\x1b[31m colors text in red
    //\x1B[0m put back text color to normal

我想知道我应该使用什么代码来检测客户端上的确认:

    //Client side there is:
    FILE * stream; // for the socket (client side)
    char buffer[100]; //to receive the server acknowledgment

    //fgets put the received stream text in the buffer:
    fgets (buffer , sizeof buffer, stream);
    
    //Here strncmp compares the buffer first 11 characters with the string "\x1b[31m220"
    if (strncmp (buffer, "\x1b[31m220",11)== 0)
    {
    printf("\x1B[48;5;%dmCommand received\x1B[0m%s\n",8,buffer);
    }

事情行不通。我想知道我应该放什么而不是"\x1b[31m220",11放在客户端中才能使事情正常进行。我怀疑颜色代码的某些字符会被解释并因此从字符串中消失,但是哪些字符呢?


这里有颜色代码的解释: stdlib and coloured output in C

4

2 回答 2

1

"\x1b[31m220"8 个字符,而不是 11个。将在此字符串和缓冲区中的strncmp第 9 个字符处失败。'\0''\x1B'

于 2020-06-28T08:32:13.557 回答
1

让您的生活更轻松,让编译器为您计算大小:

#define COLOURCODE "\x1b[31m220"

if (strncmp (buffer, COLOURCODE, sizeof(COLOURCODE) - 1)== 0)
于 2020-06-28T09:13:40.930 回答