Last active
August 11, 2017 20:30
-
-
Save mihalicyn/965c7cc24edcc4f4a72ce620822bf8b6 to your computer and use it in GitHub Desktop.
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 | |
error_reporting(E_ALL); | |
echo "TCP/IP Connection\n"; | |
$port = 23; | |
$address = gethostbyname('towel.blinkenlights.nl'); | |
$logfile = 'socket.log'; | |
unlink($logfile); | |
function wlog($msg) { | |
global $logfile; | |
file_put_contents($logfile, $msg, FILE_APPEND | LOCK_EX); | |
} | |
/* Create a TCP/IP socket. */ | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
if ($socket === false) { | |
wlog("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"); | |
} else { | |
wlog("OK.\n"); | |
} | |
//socket_set_nonblock($socket); | |
wlog("Attempting to connect to '$address' on port '$port'..."); | |
$result = socket_connect($socket, $address, $port); | |
if ($result === false) { | |
wlog("socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n"); | |
} else { | |
wlog("OK.\n"); | |
} | |
//socket_set_nonblock($socket); | |
/* | |
$in = "HEAD / HTTP/1.1\r\n"; | |
$in .= "Host: php.net\r\n"; | |
$in .= "Connection: Close\r\n\r\n"; | |
$out = ''; | |
wlog("Sending HTTP HEAD request..."); | |
socket_write($socket, $in, strlen($in)); | |
wlog("OK.\n"); | |
*/ | |
wlog("Reading response:\n\n"); | |
$data = 'This is my buffer.'; | |
$buf = ''; | |
//while (/*false !==*/ ($bytes = socket_recv($socket, $buf, 1024, MSG_WAITALL))) { | |
while (($buf = socket_read($socket, 1024))) { | |
$bytes = strlen($buf); | |
wlog("Read [$buf] $bytes bytes from socket_recv().\n"); | |
$data .= $buf; | |
//flush(); | |
//echo "Read $bytes bytes"; | |
echo $buf; | |
} | |
wlog("socket_recv() cycle finished; reason: " . socket_strerror(socket_last_error($socket)) . "\n"); | |
socket_close($socket); | |
wlog($data . "\n"); | |
wlog("OK.\n\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment