如果输出缓冲区有数据,在调用bufferevent_free之后该怎么办?

时间:2018-12-07 16:11:52

标签: c libevent

对于已连接的bufferevent(bev)

  1. 客户致电shutdown(fd, SHUT_WR);
  2. 服务器收到BEV_EVENT_EOF
  3. 如果evbuffer_get_length(bufferevent_get_output(bev)) > 0,请致电bufferevent_free(bev)

该怎么办?发送所有数据并免费还是放弃数据并免费?

如果能帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

libevent将放弃数据。

作为打击:

  1. 发送10 M或100 M数据
  2. 致电shutdown(fd, SHUT_WR);
  3. read数据,直到EOF

结果:

send 10M 
send: 10485760
read: 10485760

send 100M
send: 104857600
read: 29593600

因此服务器将放弃数据

以下是测试code

回显服务器:https://github.com/nmathewson/libevent-book/blob/master/examples_R8/R8_echo_server.c

回显客户端:

#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>

void test(int n) {
  const char* server_ip   = "127.0.0.1";  
  uint16_t    server_port = 9876;

  struct sockaddr_in server_addr;
  bzero(&server_addr, sizeof server_addr);
  server_addr.sin_family = AF_INET;
  server_addr.sin_port   = htons(server_port);
  inet_pton(AF_INET, server_ip, &server_addr.sin_addr);

  int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  connect(client_socket, (struct sockaddr*)(&server_addr), (socklen_t)(sizeof server_addr));

  char buf[1024];
  int send_count = 0;
  int read_count = 0;
  for (int i = 0; i != n; ++i)
    for (int j = 0; j != 1024; ++j) {
      ssize_t ret = write(client_socket, buf, sizeof(buf));
      if (ret == -1) {
        perror("error");
        exit(-1);
      }
      send_count += ret;
    }

  shutdown(client_socket, SHUT_WR);

  for (;;) {
    ssize_t ret = read(client_socket, buf, sizeof(buf) - 1);
    if (ret == -1) {
      perror("error");
      exit(-1);
    }
    if (ret == 0)
      break;
    read_count += ret;
  }
  printf("send: %d\n", send_count);
  printf("read: %d\n", read_count);
}

int main() {
  printf("send 10M \n");
  test(10);
  printf("\nsend 100M \n");
  test(100);

  return 0;
}