Libevent HTTP Client implementation program in PHP

Source: Internet
Author: User

PHP Libevent HTTP

The code is as follows Copy Code

<?php
Request Completion Callback
function _request_handler ($req, $base) {
Global $pend _req;
Echo __function__, Php_eol;

if (Is_null ($req)) {
echo "Timed out\n";
} else {
$response _code = $req->getresponsecode ();

if ($response _code = = 0) {
echo "Connection refused\n";
} elseif ($response _code!= 200) {
echo "Unexpected response: $response _code\n";
} else {
echo "Success: $response _code\n";
/*
$buf = $req->getinputbuffer ();
echo "body:\n";
while ($s = $buf->readline (eventbuffer::eol_any)) {
Echo $s, php_eol;
}
*/
}
}
$pend _req--;
Exit loop
if (! $pend _req) {
$base = $conn->getbase ();
$base->exit (NULL);
}
Free memory
Unset ($req);
Unset ($conn);
}

$address = "Www.111cn.net";
$pend _req = 0;
$port = 80;
Initializing event Base
$base = new Eventbase ();
echo "Event method used:", $base->getmethod (), Php_eol;
Using asynchronous DNS
$dns _base = new Eventdnsbase ($base, TRUE);
$f = fopen ("./50000.txt", "R");
while (!feof ($f))
{
$line = fgets ($f);
Echo $address;
$address = Trim ($line);
New HTTP connection event to base
$conn = new Eventhttpconnection ($base, $dns _base, $address, $port);
$conn->settimeout (1);
Set Request callback
$req = new Eventhttprequest ("_request_handler", $conn);

$req->addheader ("Host", $address, Eventhttprequest::output_header);
$req->addheader ("Content-length", "0", Eventhttprequest::output_header);
$conn->makerequest ($req, Eventhttprequest::cmd_get, "/");
$pend _req++;
}
Fclose ($f);
Event Main Loop
$base->loop ();
?>

C language edition,

The code is as follows Copy Code

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <evhttp.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/bufferevent.h>
typedef struct MY_STRUCT_S my_struct_t;

struct my_struct_s {
struct Evhttp_connection *conn;
struct Evhttp_request *req;
struct Evhttp_uri *uri;
struct event *cleanup;
};

struct Event_base *base_primary;

Char *trimwhitespace (char *str)
{
Char *end;

Trim Leading space
while (Isspace (*STR)) str++;

if (*str = 0)//all spaces?
return str;

Trim Trailing space
end = str + strlen (str)-1;
while (End > str && isspace (*end)) end--;

Write new NULL terminator
* (end+1) = 0;

return str;
}

void Connection_free (int sock, short which, void *arg) {
printf ("Freeing connection!!! The socket ' s FD would have been closed when the HTTP request ended and the->req object would have free ' been ');

Get our Structure object
my_struct_t *mystruct = arg;

Cleanup Our Properties
Event_free (Mystruct->cleanup);
Evhttp_connection_free (Mystruct->conn);
Evhttp_request_free (Mystruct->req);
Evhttp_uri_free (Mystruct->uri);

Free our custom structure
Free (mystruct);
}

void Http_request_done (struct evhttp_request *req, void *arg) {

Get our custom struct
my_struct_t *mystruct = arg;

Setup Our timeout information (we delay 5 seconds)
struct Timeval Timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;

ADD This structure to we cleanup base to is cleaned up synchronously
Todo:probably not the best way to cleanup and event, but it ' l work for the purposes of illustration.
This way would ensure no race conditions exist, but it's probably not the most efficient in how to depending many , etc we ' re dealing with.
Mystruct->cleanup = Evtimer_new (Base_primary, Connection_free, (void *) mystruct);
Evtimer_add (Mystruct->cleanup, &timeout);

printf ("Http_request_done, we put our custom strucutre into the A cleanup event to be freed!\n");
}

int Http_req (char *uri) {

Allocate our custom Struture
my_struct_t *mystruct = malloc (sizeof (my_struct_t));

Create our EVHTP connection and request
Mystruct->uri = Evhttp_uri_parse (URI);
Mystruct->conn = Evhttp_connection_base_new (base_primary, NULL, URI, 80);
Mystruct->req = Evhttp_request_new (Http_request_done, mystruct);
Evhttp_add_header (Evhttp_request_get_output_headers (Mystruct->req), "Host", "localhost");
Evhttp_add_header (Evhttp_request_get_output_headers (Mystruct->req), "Connection", "close");
Evhttp_make_request (Mystruct->conn, Mystruct->req, Evhttp_req_get, URI);
Evhttp_connection_set_timeout (Mystruct->req->evcon, 2);
return 1;
}


Define our primary function
int main (int argc, char *argv[]) {

Initialize Our Bases
Base_primary = Event_base_new ();

Char filename[] = "/tmp/50000.txt"; Filename
FILE *FP;
Char strline[1024]; The maximum number of characters per line read
Char *host;
if (fp = fopen (filename, "r") = = NULL)//To determine whether the file exists and is readable
{
printf ("error!");
return-1;
}

while (!feof (FP))
{
Fgets (STRLINE,1024,FP); Read one line
host = StrLine;
Host = Trimwhitespace (host);
printf ("%s", host); Output
Http_req (host);
}
Fclose (FP);

//
Event_base_loop (base_primary);
Event_base_dispatch (base_primary);

Free our primary base
Event_base_free (base_primary);
return 1;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.