/
examples.xml
1317 lines (1113 loc) · 33.8 KB
/
examples.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<chapter xml:id="event.examples" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
&reftitle.examples;
<example>
<title>Simple HTTP client</title>
<programlisting role="php">
<![CDATA[
<?php
// Read callback
function readcb($bev, $base) {
//$input = $bev->input; //$bev->getInput();
//$pos = $input->search("TTP");
$pos = $bev->input->search("TTP");
while (($n = $bev->input->remove($buf, 1024)) > 0) {
echo $buf;
}
}
// Event callback
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}
echo "Closing\n";
$base->exit();
exit("Done\n");
}
}
if ($argc != 3) {
echo <<<EOS
Trivial HTTP 0.x client
Syntax: php {$argv[0]} [hostname] [resource]
Example: php {$argv[0]} www.google.com /
EOS;
exit();
}
$base = new EventBase();
$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
exit("Failed to init DNS Base\n");
}
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
"readcb", /* writecb */ NULL, "eventcb"
);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}
//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);
$output = $bev->output; //$bev->getOutput();
if (!$output->add(
"GET {$argv[2]} HTTP/1.0\r\n".
"Host: {$argv[1]}\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}
if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
exit("Can't connect to host {$argv[1]}\n");
}
$base->dispatch();
?>
]]>
</programlisting>
&example.outputs.similar;
<screen>
<![CDATA[
Connected.
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 Mar 2013 18:47:48 GMT
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Age: 133438
Expires: Sat, 30 Mar 2013 05:39:28 GMT
Connection: close
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done
]]>
</screen>
</example>
<example>
<title>HTTP client using asynchronous DNS resolver</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* 1. Connect to 127.0.0.1 at port 80
* by means of EventBufferEvent::connect().
*
* 2. Request /index.cphp via HTTP/1.0
* using the output buffer.
*
* 3. Asyncronously read the response and print it to stdout.
*/
// Read callback
function readcb($bev, $base) {
$input = $bev->getInput();
while (($n = $input->remove($buf, 1024)) > 0) {
echo $buf;
}
}
// Event callback
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}
echo "Closing\n";
$base->exit();
exit("Done\n");
}
}
$base = new EventBase();
echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}
echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);
echo "step 3\n";
// Send request
$output = $bev->getOutput();
if (!$output->add(
"GET /index.cphp HTTP/1.0\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}
/* Connect to the host syncronously.
We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
exit("Can't connect to host\n");
}
// Dispatch pending events
$base->dispatch();
?>
]]>
</programlisting>
</example>
<example>
<title>Echo server</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* Simple echo server based on libevent's connection listener.
*
* Usage:
* 1) In one terminal window run:
*
* $ php listener.php 9881
*
* 2) In another terminal window open up connection, e.g.:
*
* $ nc 127.0.0.1 9881
*
* 3) start typing. The server should repeat the input.
*/
class MyListenerConnection {
private $bev, $base;
public function __destruct() {
$this->bev->free();
}
public function __construct($base, $fd) {
$this->base = $base;
$this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);
$this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
array($this, "echoEventCallback"), NULL);
if (!$this->bev->enable(Event::READ)) {
echo "Failed to enable READ\n";
return;
}
}
public function echoReadCallback($bev, $ctx) {
// Copy all the data from the input buffer to the output buffer
// Variant #1
$bev->output->addBuffer($bev->input);
/* Variant #2 */
/*
$input = $bev->getInput();
$output = $bev->getOutput();
$output->addBuffer($input);
*/
}
public function echoEventCallback($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
echo "Error from bufferevent\n";
}
if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
//$bev->free();
$this->__destruct();
}
}
}
class MyListener {
public $base,
$listener,
$socket;
private $conn = array();
public function __destruct() {
foreach ($this->conn as &$c) $c = NULL;
}
public function __construct($port) {
$this->base = new EventBase();
if (!$this->base) {
echo "Couldn't open event base";
exit(1);
}
// Variant #1
/*
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($this->socket, '0.0.0.0', $port)) {
echo "Unable to bind socket\n";
exit(1);
}
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1, $this->socket);
*/
// Variant #2
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
"0.0.0.0:$port");
if (!$this->listener) {
echo "Couldn't create listener";
exit(1);
}
$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}
public function dispatch() {
$this->base->dispatch();
}
// This callback is invoked when there is data to read on $bev
public function acceptConnCallback($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it. */
$base = $this->base;
$this->conn[] = new MyListenerConnection($base, $fd);
}
public function accept_error_cb($listener, $ctx) {
$base = $this->base;
fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());
$base->exit(NULL);
}
}
$port = 9808;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}
$l = new MyListener($port);
$l->dispatch();
?>
]]>
</programlisting>
</example>
<example>
<title>SSL echo server</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* SSL echo server
*
* To test:
* 1) Run:
* $ php examples/ssl-echo-server/server.php 9998
*
* 2) in another terminal window run:
* $ socat - SSL:127.0.0.1:9998,verify=1,cafile=examples/ssl-echo-server/cert.pem
*/
class MySslEchoServer {
public $port,
$base,
$bev,
$listener,
$ctx;
function __construct ($port, $host = "127.0.0.1") {
$this->port = $port;
$this->ctx = $this->init_ssl();
if (!$this->ctx) {
exit("Failed creating SSL context\n");
}
$this->base = new EventBase();
if (!$this->base) {
exit("Couldn't open event base\n");
}
$this->listener = new EventListener($this->base,
array($this, "ssl_accept_cb"), $this->ctx,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1, "$host:$port");
if (!$this->listener) {
exit("Couldn't create listener\n");
}
$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}
function dispatch() {
$this->base->dispatch();
}
// This callback is invoked when there is data to read on $bev.
function ssl_read_cb($bev, $ctx) {
$in = $bev->input; //$bev->getInput();
printf("Received %zu bytes\n", $in->length);
printf("----- data ----\n");
printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));
$bev->writeBuffer($in);
}
// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occurred
function ssl_event_cb($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
// Fetch errors from the SSL error stack
while ($err = $bev->sslError()) {
fprintf(STDERR, "Bufferevent error %s.\n", $err);
}
}
if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
$bev->free();
}
}
// This callback is invoked when a client accepts new connection
function ssl_accept_cb($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it.
$this->bev = EventBufferEvent::sslSocket($this->base, $fd, $this->ctx,
EventBufferEvent::SSL_ACCEPTING, EventBufferEvent::OPT_CLOSE_ON_FREE);
if (!$this->bev) {
echo "Failed creating ssl buffer\n";
$this->base->exit(NULL);
exit(1);
}
$this->bev->enable(Event::READ);
$this->bev->setCallbacks(array($this, "ssl_read_cb"), NULL,
array($this, "ssl_event_cb"), NULL);
}
// This callback is invoked when we failed to setup new connection for a client
function accept_error_cb($listener, $ctx) {
fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());
$this->base->exit(NULL);
}
// Initialize SSL structures, create an EventSslContext
// Optionally create self-signed certificates
function init_ssl() {
// We *must* have entropy. Otherwise there's no point to crypto.
if (!EventUtil::sslRandPoll()) {
exit("EventUtil::sslRandPoll failed\n");
}
$local_cert = __DIR__."/cert.pem";
$local_pk = __DIR__."/privkey.pem";
if (!file_exists($local_cert) || !file_exists($local_pk)) {
echo "Couldn't read $local_cert or $local_pk file. To generate a key\n",
"and self-signed certificate, run:\n",
" openssl genrsa -out $local_pk 2048\n",
" openssl req -new -key $local_pk -out cert.req\n",
" openssl x509 -req -days 365 -in cert.req -signkey $local_pk -out $local_cert\n";
return FALSE;
}
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
EventSslContext::OPT_LOCAL_CERT => $local_cert,
EventSslContext::OPT_LOCAL_PK => $local_pk,
//EventSslContext::OPT_PASSPHRASE => "echo server",
EventSslContext::OPT_VERIFY_PEER => true,
EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));
return $ctx;
}
}
// Allow to override the port
$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port\n");
}
$l = new MySslEchoServer($port);
$l->dispatch();
?>
]]>
</programlisting>
</example>
<example>
<title>Signal handler</title>
<programlisting role="php">
<![CDATA[
<?php
/*
Launch it in a terminal window:
$ php examples/signal.php
In another terminal window find out the pid and send SIGTERM, e.g.:
$ ps aux | grep examp
ruslan 3976 0.2 0.0 139896 11256 pts/1 S+ 10:25 0:00 php examples/signal.php
ruslan 3978 0.0 0.0 9572 864 pts/2 S+ 10:26 0:00 grep --color=auto examp
$ kill -TERM 3976
At the first terminal window you should catch the following:
Caught signal 15
*/
class MyEventSignal {
private $base;
function __construct($base) {
$this->base = $base;
}
function eventSighandler($no, $c) {
echo "Caught signal $no\n";
event_base_loopexit($c->base);
}
}
$base = event_base_new();
$c = new MyEventSignal($base);
$no = SIGTERM;
$ev = evsignal_new($base, $no, array($c,'eventSighandler'), $c);
evsignal_add($ev);
event_base_loop($base);
?>
]]>
</programlisting>
</example>
<example>
<title>Use libevent's loop to process requests of `eio' extension</title>
<programlisting role="php">
<![CDATA[
<?php
// Callback for eio_nop()
function my_nop_cb($d, $r) {
echo "step 6\n";
}
$dir = "/tmp/abc-eio-temp";
if (file_exists($dir)) {
rmdir($dir);
}
echo "step 1\n";
$base = new EventBase();
echo "step 2\n";
eio_init();
eio_mkdir($dir, 0750, EIO_PRI_DEFAULT, "my_nop_cb");
$event = new Event($base, eio_get_event_stream(),
Event::READ | Event::PERSIST, function ($fd, $events, $base) {
echo "step 5\n";
while (eio_nreqs()) {
eio_poll();
}
$base->stop();
}, $base);
echo "step 3\n";
$event->add();
echo "step 4\n";
$base->dispatch();
echo "Done\n";
?>
]]>
</programlisting>
</example>
<example>
<title>Miscellaneous</title>
<programlisting role="php">
<![CDATA[
<?php
/* {{{ Config & supported stuff */
echo "Supported methods:\n";
foreach (Event::getSupportedMethods() as $m) {
echo $m, PHP_EOL;
}
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' method avoided\n";
}
// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;
echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print "ET - edge-triggered IO\n";
($features & EventConfig::FEATURE_O1) and print "O1 - O(1) operation for adding/deleting events\n";
($features & EventConfig::FEATURE_FDS) and print "FDS - arbitrary file descriptor types, and not just sockets\n";
// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
echo "FDS feature is now required\n";
$base = new EventBase($cfg);
($base->getFeatures() & EventConfig::FEATURE_FDS)
and print "FDS - arbitrary file descriptor types, and not just sockets\n";
}
/* }}} */
/* {{{ Base */
$base = new EventBase();
$event = new Event($base, STDIN, Event::READ | Event::PERSIST, function ($fd, $events, $arg) {
static $max_iterations = 0;
if (++$max_iterations >= 5) {
/* exit after 5 iterations with timeout of 2.33 seconds */
echo "Stopping...\n";
$arg[0]->exit(2.33);
}
echo fgets($fd);
}, array (&$base));
$event->add();
$base->loop();
/* Base }}} */
?>
]]>
</programlisting>
</example>
<example>
<title>Simple HTTP server</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* Simple HTTP server.
*
* To test it:
* 1) Run it on a port of your choice, e.g.:
* $ php examples/http.php 8010
* 2) In another terminal connect to some address on this port
* and make GET or POST request(others are turned off here), e.g.:
* $ nc -t 127.0.0.1 8010
* POST /about HTTP/1.0
* Content-Type: text/plain
* Content-Length: 4
* Connection: close
* (press Enter)
*
* It will output
* a=12
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* $ nc -t 127.0.0.1 8010
* GET /dump HTTP/1.0
* Content-Type: text/plain
* Content-Encoding: UTF-8
* Connection: close
* (press Enter)
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
* (press Enter)
*
* $ nc -t 127.0.0.1 8010
* GET /unknown HTTP/1.0
* Connection: close
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* 3) See what the server outputs on the previous terminal window.
*/
function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 2;
if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}
echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);
echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
echo "\n >> Reading input buffer ...\n";
$buf = $req->getInputBuffer();
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
echo "No more data in the buffer\n";
}
function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
$port = 8010;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}
$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);
$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");
$http->bind("0.0.0.0", 8010);
$base->loop();
?>
]]>
</programlisting>
&example.outputs.similar;
<screen>
<![CDATA[
a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
]]>
</screen>
</example>
<example>
<title>Simple HTTPS server</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* Simple HTTPS server.
*
* 1) Run the server: `php examples/https.php 9999`
* 2) Test it: `php examples/ssl-connection.php 9999`
*/
function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 200;
if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}
echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);
echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
$buf = $req->getInputBuffer();
echo "\n >> Reading input buffer (", $buf->length, ") ...\n";
while ($s = $buf->read(1024)) {
echo $s;
}
echo "\nNo more data in the buffer\n";
}
function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}
function _http_400($req) {
$req->sendError(400);
}
function _init_ssl() {
$local_cert = __DIR__."/ssl-echo-server/cert.pem";
$local_pk = __DIR__."/ssl-echo-server/privkey.pem";
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
EventSslContext::OPT_LOCAL_CERT => $local_cert,
EventSslContext::OPT_LOCAL_PK => $local_pk,
//EventSslContext::OPT_PASSPHRASE => "test",
EventSslContext::OPT_ALLOW_SELF_SIGNED => true,
));
return $ctx;
}
$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}
$ip = '0.0.0.0';
$base = new EventBase();
$ctx = _init_ssl();
$http = new EventHttp($base, $ctx);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);
$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setCallback("/err400", "_http_400");
$http->setDefaultCallback("_http_default", "custom data value");
$http->bind($ip, $port);
$base->dispatch();
]]>
</programlisting>
</example>
<example>
<title>OpenSSL connection</title>
<programlisting role="php">
<![CDATA[
<?php
/*
* Sample OpenSSL client.
*
* Usage:
* 1) Launch a server, e.g.:
* $ php examples/https.php 9999
*
* 2) Launch the client in another terminal:
* $ php examples/ssl-connection.php 9999
*/
function _request_handler($req, $base) {
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;
}
}
}
$base->exit(NULL);
}
function _init_ssl() {
$ctx = new EventSslContext(EventSslContext::SSLv3_CLIENT_METHOD, array ());
return $ctx;
}
// Allow to override the port
$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port\n");
}
$host = '127.0.0.1';
$ctx = _init_ssl();
if (!$ctx) {
trigger_error("Failed creating SSL context", E_USER_ERROR);
}
$base = new EventBase();
if (!$base) {
trigger_error("Failed to initialize event base", E_USER_ERROR);
}
$conn = new EventHttpConnection($base, NULL, $host, $port, $ctx);
$conn->setTimeout(50);
$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $host, EventHttpRequest::OUTPUT_HEADER);
$buf = $req->getOutputBuffer();
$buf->add("<html>HTML TEST</html>");
//$req->addHeader("Content-Length", $buf->length, EventHttpRequest::OUTPUT_HEADER);
//$req->addHeader("Connection", "close", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_POST, "/dump");
$base->dispatch();
echo "END\n";
?>
]]>
</programlisting>
</example>
<example>
<title>
<function>EventHttpConnection::makeRequest</function> example</title>
<programlisting role="php">
<![CDATA[
<?php
function _request_handler($req, $base) {
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;
}
}
}
$base->exit(NULL);
}
$address = "127.0.0.1";
$port = 80;
$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);