Created
October 7, 2022 15:58
-
-
Save TomZhuPlanetart/b2443560cb9527c0b41a8558169a40dd to your computer and use it in GitHub Desktop.
Making async TCP connection with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* User: Tom.Zhu<[email protected]> | |
* Date: 2022/10/7 | |
* Time: 23:34 | |
*/ | |
$base = new EventBase(); | |
$start = microtime(true); | |
//$client = stream_socket_client("tcp://180.101.49.12:80", $errorCode, $errorMsg, 10); | |
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
socket_set_nonblock($sock); | |
$bev = new EventBufferEvent($base, $sock, 0, function($bev){ | |
do { | |
$data = $bev->getInput()->read(10240); | |
echo $data; | |
} while (strlen($data) > 0); | |
}, null, null); | |
$v = socket_connect($sock, '180.101.49.12', 80); | |
$bev->enable(Event::READ | Event::WRITE); | |
$output = $bev->getOutput(); | |
$output->add( | |
"GET / HTTP/1.1\r\n". | |
"Host: www.baidu.com\r\n". | |
"Connection: close\r\n". | |
"\r\n" | |
); | |
$end = microtime(true); | |
echo "connection time: ", $end - $start, "\n"; | |
$base->loop(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment