单机上万客户端连接

转: http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-3


#include <sys/types.h>
#include <sys/time.h>
#include <sys/queue.h>
#include <stdlib.h>
#include <err.h>
#include <event.h>
#include <evhttp.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <pthread.h>

#define BUFSIZE 4096
#define NUMCONNS 62000
#define SERVERADDR "74.125.71.99"
#define SERVERPORT 80
#define SLEEP_MS 10

char buf[BUFSIZE];

int bytes_recvd = 0;
int chunks_recvd = 0;
int closed = 0;
int connected = 0;

// called per chunk received
void chunkcb(struct evhttp_request * req, void * arg)
{
int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
//printf("Read %d bytes: %s\n", s, &buf);
bytes_recvd += s;
chunks_recvd++;
if(connected >= NUMCONNS && chunks_recvd%10000==0)
printf(">Chunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
}

// gets called when request completes
void reqcb(struct evhttp_request * req, void * arg)
{
closed++;
}

int main(int argc, char **argv)
{
event_init();
struct evhttp *evhttp_connection;
struct evhttp_request *evhttp_request;
char addr[16];
char path[32]; // eg: "/test/123"
int i,octet;
for(octet=1; octet<=17; octet++){
sprintf(&addr, "172.17.3.%d", octet);
for(i=1;i<=NUMCONNS;i++) {
evhttp_connection = evhttp_connection_new(SERVERADDR, SERVERPORT);
evhttp_connection_set_local_address(evhttp_connection, &addr);
evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
evhttp_request = evhttp_request_new(reqcb, NULL);
evhttp_request->chunk_cb = chunkcb;
sprintf(&path, "/?%d", ++connected);
if(i%100==0) printf("Req: %s\t->\t%s\n", addr, &path);
evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
event_loop( EVLOOP_NONBLOCK );
if( connected % 200 == 0 )
printf("\nChunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
usleep(SLEEP_MS*1000);
}
}
event_dispatch();
return 0;
}


$ gcc -o httpclient httpclient.c -levent
$ ./httpclient


# netstat -n | awk '/^tcp/ {t[$NF]++}END{for(state in t){print state, t[state]} }'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值