To use the fsockopen function, you must first enable allow_url_open = on in php. ini;
Fsockopen is the encapsulation of socket Client code. This function encapsulates socket_create and socket_connect.
Server code: server. php
Copy codeThe Code is as follows: <? Php
Error_reporting (E_ALL );
Set_time_limit (0 );
$ Address = '1970. 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 ";
}
// Bind
If (socket_bind ($ sock, $ address, $ port) === false ){
Echo "socket_bind () failed: reason:". socket_strerror (socket_last_error ($ sock). "\ n ";
}
// Listen
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;
}
// Send welcome to the 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); // obtain the information sent from the client.
$ Talkback = "2. received message: $ buf \ n ";
Echo $ talkback;
If (false === socket_write ($ msgsock, $ talkback, strlen ($ talkback) {// return 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: fsocket. phpCopy codeThe Code is 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 ";
Fputs ($ fp, $ in );
While (! Feof ($ fp )){
Echo fgets ($ fp, 128 );
}
Fclose ($ fp );
}