我写了一个简单的程序,使用libevent与这个示例代码同时连接到Web服务器
#include <stdio.h>
#include <event2/event.h>
#include <evhttp.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
int success_count = 0;
int failure_count = 0;
time_t start,end;
void _reqhandler(struct evhttp_request *req, void *state)
{
printf("in _reqhandler. state == %s\n", (char *) state);
if (req == NULL) {
printf("timed out!\n");
failure_count ++;
} else if (req->response_code == 0) {
printf("connection refused!\n");
failure_count++;
} else if (req->response_code != 200) {
printf("error: %u %s\n", req->response_code, req->response_code_line);
failure_count++;
} else {
printf("success: %u %s\n", req->response_code, req->response_code_line);
success_count++;
}
evhttp_connection_free((evhttp_connection*)state);
}
void* thread_func(void* arg)
{
printf("starting event loop..\n");
sleep(1);
event_base_dispatch((struct event_base*)arg);
printf("returning");
}
int main(int argc, char *argv[])
{
struct event_base* base = event_init();
printf("Using Libevent with backend method %s.",event_base_get_method(base));
pthread_t id;
int ret = pthread_create(&id,NULL,thread_func,base);
int x = 10;
start = time (NULL);
while(x--){
printf("%s\n","adding");
const char *addr = "74.125.131.103";
unsigned int port = 80;
struct evhttp_connection *conn;
struct evhttp_request *req;
//printf("initializing libevent subsystem..\n");
conn = evhttp_connection_new(addr, port);
evhttp_connection_set_timeout(conn, 5);
req = evhttp_request_new(_reqhandler, (void *)conn);
evhttp_add_header(req->output_headers, "Host", addr);
evhttp_add_header(req->output_headers, "Content-Length", "0");
evhttp_make_request(conn, req, EVHTTP_REQ_GET, "/");
}
pthread_join( id, NULL);
end = time(NULL);
double dif = difftime(end,start);
printf("total seconds taken: %.2lf for %d success connections and %d failed
connections\n", dif, success_count,failure_count);
return 0;
}
我在带有centos的vmware融合上运行它。问题是,当我运行它时,我只得到服务器拒绝连接。在对wireshark的进一步调查中,我意识到这段代码正在从后面发出HTTP POST请求而不是GET,因此连接被拒绝了。现在相同的代码在我的mac或ubuntu机器上运行良好。这似乎是虚拟操作系统的配置问题。任何人都可以指出它可能是什么?这就是我的虚拟操作系统发送的内容:
POST / HTTP/1.1
Host: 74.125.131.103
Content-Length: 0
HTTP/1.1 405 Method Not Allowed