Fsockopen function can be used, first of all, to open the php.ini in the Allow_url_open=on;
Fsockopen is the encapsulation of the socket client code, which encapsulates the socket_create,socket_connect.
Server-side code: server.php
Copy Code code as follows:
<?php
Error_reporting (E_all);
Set_time_limit (0);
$address = ' 127.0.0.1 ';
$port = 10008;
Create Port
if (($sock = Socket_create (Af_inet, Sock_stream, sol_tcp)) = = False) {
echo "Socket_create () Failed:reason:". Socket_strerror (Socket_last_error ()). "\ n";
}
Binding
if (Socket_bind ($sock, $address, $port) = = False) {
echo "Socket_bind () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";
}
Listening
if (Socket_listen ($sock, 5) = = False) {
echo "Socket_bind () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). "\ n";
}
while (true) {
Get a link
if (($msgsock = socket_accept ($sock)) = = False) {
echo "Socket_accepty () Failed:reason:". Socket_strerror (Socket_last_error ($sock)). " \ n ";
Break
}
Welcome sent to Client
$msg = "1.<font color= ' red ' >server send:welcome</font><br/>";
Socket_write ($msgsock, $msg, strlen ($msg)); Return information to the client
Echo ' read client message\n ';
$buf = Socket_read ($msgsock, 8192); Get the information that the client sent over
$talkback = "2.received message: $buf \ n";
Echo $talkback;
if (false = = = Socket_write ($msgsock, $talkback, strlen ($talkback)) {//return information to 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: fsocket.php
Copy Code code as follows:
<?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);
}