Application example analysis based on php socket of fsockopen

  • 2020-06-03 06:05:27
  • OfStack

The fsockopen function can be applied by starting allow_url_open=on in ES1en.ini;
fsockopen is an encapsulation of the socket client code, which encapsulates socket_create,socket_connect.
Server-side code: ES15en.php

<?php
error_reporting(E_ALL);
set_time_limit(0);
$address = '127.0.0.1';
$port = 10008;
// Create a port 
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed:reason:" . socket_strerror(socket_last_error()) . "\n";
}
// The binding 
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
}
// Listening to the 
if (socket_listen($sock, 5) === false) {
echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
}
while (true) {
// get 1 A link 
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";
break;
}
//welcome  Send to the client 
$msg = "1.<font color='red'>server send:welcome</font><br/>";
socket_write($msgsock, $msg, strlen($msg)); // Returns information to the client 
echo 'read client message\n';
$buf = socket_read($msgsock, 8192); // Get the information sent by the client 
$talkback = "2.received message:$buf\n";
echo $talkback;
if (false === socket_write($msgsock, $talkback, strlen($talkback))) { // Returns information to the client 
echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n";
} else {
echo 'send success';
}
socket_close($msgsock);
}
socket_close($sock);

Client code: ES20en.php

<?php
$fp = fsockopen("127.0.0.1", 10008, &$errno, &$errstr, 10);
if (!$fp) {
echo $errstr . " (". $errno . ")<br>n";
} else {
$in = "HEAD / http/1.1\r\n";
$in .= "HOST: localhost \r\n";
$in .= "Connection: close\r\n\r\n";
fputs($fp, $in);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}


Related articles: