如何多次调用bufferevent_write?

时间:2016-04-05 03:11:06

标签: c libevent

我是libevent的新手,下面我的程序非常简单。我想多次打电话给bufferevent_write,但似乎它只适用于第一次。

int main(int argc, char const *argv[])
{
    struct sockaddr_in serv_addr;
    struct hostent *server;

    int portno = atoi(argv[2]);

    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(portno);

    struct event_base* base = event_base_new();

    evutil_socket_t fd;
    fd = socket(AF_INET, SOCK_STREAM, 0);
    struct bufferevent* con_conn = bufferevent_socket_new(base,fd,BEV_OPT_CLOSE_ON_FREE);

    bufferevent_setcb(con_conn,NULL,NULL,NULL,NULL);
    bufferevent_enable(con_conn,EV_READ|EV_WRITE|EV_PERSIST);
    bufferevent_socket_connect(con_conn,(struct sockaddr*)&serv_addr,sizeof(struct sockaddr_in));
    int enable = 1;
    if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&enable, sizeof(enable)) < 0)
        printf("TCP_NODELAY SETTING ERROR!\n");

    char data[5] = "sss";
    int i;
    for (i = 0; i < 2; ++i)
    {
        int rc = bufferevent_write(con_conn,data,5);
        printf("rc is %d\n", rc);
    }
    event_base_dispatch(base);  

    return 0;
}

我的服务器端:

void error(char *msg)
{
    perror(msg);
    exit(1);
}

int main(int argc, char *argv[])
{
     int sockfd, newsockfd, portno, clilen;
     char buffer[256];
     struct sockaddr_in serv_addr, cli_addr;
     int n;
     if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         //exit(1);
     }
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = atoi(argv[1]);
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              error("ERROR on binding");
     listen(sockfd,5);
     clilen = sizeof(cli_addr);
     printf("waiting...\n");
     newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
     sleep(5);
     bzero(buffer,256);
     n = read(newsockfd,buffer,255);
     if (n < 0) error("ERROR reading from socket");
     printf("Here is the message: %s\n",buffer);

     return 0; 
}

0 个答案:

没有答案