简体   繁体   English

在C中从客户端向服务器发送多个答复

[英]Send multiple replies to server from client in C

My server sends me the following message: 我的服务器向我发送以下消息:

INFO 123456\\n (number may vary) INFO 123456 \\ n(数字可能有所不同)

I am supposed to respond to the server with: 我应该用以下方式响应服务器:

REPLY 123456\\n - matching reply 回复123456 \\ n-匹配的回复

Currently, my code is correctly sending one reply. 目前,我的代码正确发送了一个回复。 However, the server is returning with an error when I try to send a second reply. 但是,当我尝试发送第二个答复时,服务器返回错误。 I feel like it may have something to do with the reply_message char array? 我觉得这可能与Reply_message char数组有关? Any thoughts on this? 有什么想法吗? I posted my code below. 我在下面发布了我的代码。 Thanks! 谢谢!

        while(1) {
        server_reply[0] = '\0';
        printf("Server Reply: %s\n", server_reply);
        n = recv(sockfd, server_reply, sizeof(server_reply), 0);
        if (n <= 0) {
            printf("Receive failed\n");
            return 1;
        }
        printf("Message Recieved from Server: %s\n", server_reply);

        if (server_reply) {
            char checkInfo[5];
            memcpy(checkInfo, &server_reply, 4);
            checkInfo[4] = '\0';

            if (strcmp(checkInfo, "INFO") == 0) {
                char reply_message[sizeof(server_reply) + 1];
                memset(reply_message, 0, sizeof(reply_message));
                strncpy(reply_message, "REPLY ", sizeof reply_message - 1);
                char *replyNumber = server_reply;
                replyNumber++;
                replyNumber++;
                replyNumber++;
                replyNumber++;
                replyNumber++;
                strcat(reply_message, replyNumber);
                strcat(reply_message, "\n");
                printf("Reply Message: %s\n", reply_message);

                if ((send(sockfd, reply_message, strlen(reply_message), 0)) < 0) {
                    printf("Send failed");
                    close(sockfd);
                    return 1;
                }
                printf("Message Sent: %s\n", reply_message);
                reply_message[0] = '\0';
            }
        }
    }

I also posted the error I'm receiving. 我还发布了我收到的错误。

在此处输入图片说明

It is understood from the above code 从上面的代码可以理解

"server_reply[0] = '\\0';"

server_reply is an array or a character pointer. server_reply是数组或字符指针。 While doing 在做的时候

"memcpy(checkInfo, &server_reply, 4);"

there is no need of "&". 不需要“&”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM