First, open the socket
Phpinfo (); Check to see if the socket extension is turned on, otherwise open in php.ini.
Second, the server-side code of the wording
<?phperror_reporting (E_all); set_time_limit (0);Ob_implicit_flush (); $address = ' 127.0.0.1 '; $port = 10005;Creating portsif ($sock = Socket_create (Af_inet, sock_stream, sol_tcp) = = = =False) {echo "Socket_create () Failed:reason: ". Socket_strerror (Socket_last_error ()). "\ n ";}Bindingif (Socket_bind ($sock, $address, $port) = = =False) {echo "Socket_bind () Failed:reason: ". Socket_strerror (Socket_last_error ($sock)). "\ n ";}Listeningif (Socket_listen ($sock, 5) = = =False) {echo "Socket_bind () Failed:reason: ". Socket_strerror (Socket_last_error ($sock)). "\ n ";}do {Get a linkif ($msgsock = socket_accept ($sock)) = = =False) {echo "Socket_accepty () Failed:reason: ". Socket_strerror (Socket_last_error ($sock))."\ n ";Break ;} //welcome sent to client $msg = "<font color= ' red ' >server send:welcome</font><br/>"; Socket_write ($ Msgsock, $msg, strlen ($msg)); Echo ' read client message\n '; $buf = Socket_read ($msgsock, 8192); $talkback = "received me Ssage: $buf \ n "; Echo $talkback; if (false = = = Socket_write ($msgsock, $talkback, strlen ($talkback))) {echo "socket_write () failed reason:". Socket_strerror (Socket_last_error ($sock)). " \ n ";} else {echo ' send success ';} Socket_close ($msgsock);} while (true); Close Socketsocket_close ($sock);? >
Server side needs to be executed in CLI mode, it is possible that the CLI mode php.ini file is loaded differently
Can be output like this
In this case there is a tem.text file in the Zhoxh directory. View Configuration File (php.ini) Path = = C:\WINDOWS. Not my php.ini file, which indicates that the php.ini file was called incorrectly. At this point we will specify the php.ini file command as follows
Note that my PHP can be executed directly when the environment variable is configured.
Third, the client
<?phpError_reporting (E_all); echo "<H2>TCP/IP connection Socket_create () Failed:reason: ". Socket_strerror (Socket_last_error ()). "\ n ";} else {echo 'Ok. \ n ";} echo "Attempting to connect to ' $address ' on port ' $service _port ' ... "; $result = Socket_connect ($socket, $address, $service _port if ($result = = = False) {echo "socket_connect () Failed.\nreason: ($result) ". Socket_strerror (Socket_last_error ($socket)). "\ n";} else {echo "OK \ n";} $in = "head/http/1.1\r\n"; $in. = "host:localhost \ r \ n"; $in. = "connection:close\r\n\r\n"; $out = ""; ech O "sending HTTP Head request ..."; Socket_write ($socket, $in, strlen ($in)); echo "ok\n"; echo "Reading response : \ n ";" while ($out = Socket_read ($socket, 8192)) {echo $out;} echo "closeing socket."; Socket_close ($socket); echo "ok. \ n";
Server
Client
Using the socket in PHP