c - 从 C 套接字读取预期数据包的最大大小

标签 c sockets tcp

我有一个客户端/服务器程序。客户端向服务器发送消息,服务器处理该消息并返回给客户端。

客户端消息的前四个字节是整个消息的大小。我还知道消息的最大大小。然而,消息的大小是可变的。

我在 while 循环中使用 read 函数来读取客户端消息

while((n = read(socket, buffer, MAX_SIZE)) != 0){
    process_message();
    write(socket, ...);
}

我想知道读取比客户端发送的字节更多的字节是否有任何危害?我可以先读取消息的大小,然后读取确切的字节数,但我想知道这是否有必要。

最佳答案

正如其他一些评论中提到的,从套接字读取可以返回任意数量的字节,最多可达请求的最大数量。

一个更好的循环,虽然仍然存在问题,但应该是这样的:

/* 4 byte message header that contains the length */
#define MSG_HEADER_SIZE 4
#define MAX_MESSAGE_LENGTH 128
struct message {
    uint32_t length;
    char body[MAX_MESSAGE_LENGTH];
};

#define BUFFER_SIZE 1024
char buffer[BUFFER_SIZE];
uint32_t buf_used = 0;

/* main loop */
while (1) {
    n = recv(socket, buffer + buf_used, sizeof(buffer) - buf_used, 0);

    if (n == -1) {
        /* handle error */
        exit(1);
    }

    if (n == 0) {
        /* connection closed, do something. */
        exit(1);
    }

    buf_used += n;

    /* check for partial/completed message(s) */
    while (buf_used >= MSG_HEADER_SIZE) {
        struct message *cur_msg = (struct message *) buffer;
        uint32_t total_msg_length;

        total_msg_length = cur_msg->length + MSG_HEADER_SIZE;

        /* is this message completed yet? */
        if (buf_used >= total_msg_length) {
            process_message(cur_msg);

            /* remove message since it has been processed */
            buf_used -= total_msg_length;

            /* this could potentially be optimized */
            memmove(buffer, buffer + total_msg_length, buf_used);
        } else {
            /* have incomplete message */
            break;
        }
    }
}

有关套接字编程的介绍,我建议查看 Beej's Guide to Network Programming .

关于c - 从 C 套接字读取预期数据包的最大大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867598/

相关文章:

C - 读取并存储数据文件以供进一步计算

python - 在 python 中读取蓝牙 LE(智能)设备的(任何)特征值

c++ - 如何在单个客户端上同时在 UDP 套接字上接收和发送数据

javascript - 使用nodejs通过tcp套接字传输数据

php - TCP CLOSE_WAIT 连接状态 - 未知原因

android - 如何在 Android 中设置 keepalive 超时?

c - OpenMP for 循环没有给出正确的结果

c - Linux进程间通信

c - 将服务器套接字绑定(bind)到端口失败 (C)

c - 如何在 C 的套接字上发送/接收字符串数组