1 */This article provides an example of socket-related functions in the PHP tutorial. If you create a socket, you will receive a socket connection and write it into a socket to initialize the connection. */2 $ IP = "127.0.0.1"; // define IP address 3 $ Port = 1000; // Define Port 4 $ socket = socket_create (af_inet, sock_stream, sol_tcp ); // create socket 5 $ bind = socket_bind ($ socket, $ IP, $ prot); // bind a socket 6 $ Listen = socket_listen ($ socket ); // listen to socket 7 $ MSG = socket_accept ($ socket); // accept a socket connection 8 $ welcome = "welcome to the PHP service/N "; // define the string 9 socket_write ($ MSG, $ welcome, strlen ($ welcome); // write a socket10 socket_close ($ socket); // close socket11 12 13 1 4 $ IP = "127.0.0.1"; // defines the IP address 15 $ Port = 1000; // defines the port 16 $ socket = socket_create (af_inet, sock_stream, sol_tcp ); // create socket17 socket_clear_error ($ socket); // clear socket error information 18 socket_close ($ socket); // disable socket19 20 21 22 $ sockets = array (); // define an array 23 24 if (! Socket_create_pair (af_unix, sock_stream, 0, $ sockets) // If the socket is not successfully created 25 {26 echo socket_strerror (socket_last_error ()); // output error message 27} 28 29 If (! Socket_write ($ sockets [0], "abcdef123n", strlen ("abcdef123n") // 30 {31 Cho socket_strerror (socket_last_error () If the socket write fails to be executed ()); // output error message 32} 33 If (! $ DATA = socket_read ($ sockets [1], strlen ("abcdef123n"), php_binary_read) // If the read information fails 34 {35 echo socket_strerror (socket_last_error ()); // output error message 36} 37 var_dump ($ data); // output socket data information 38 39 socket_close ($ sockets [0]); // disable socket140 socket_close ($ sockets [1]); // disable socket241 42 43 44 $ IP = "127.0.0.1"; // define IP address 45 $ Port = 1000; // Define Port 46 $ socket = socket_create (af_inet, sock_stream, sol_tcp); // create socket47 socket_set_nonb Lock ($ socket); // set the unlocked status to 48 socket_connect ($ socket, $ IP, $ port); // initialize the connection to 49 socket_set_block ($ sock ); // lock socket50 switch (socket_select ($ r = array ($ socket), $ W = array ($ socket), $ F = array ($ socket), 5 )) 51 {52 case echo "connection rejected! N "; 54 break; 55 case echo" successful connection N "; 57 break; 58 Case echo" connection timeout N "; 60 break; 61} 62 63 64 65 66 class socketlistener extends socket67 {68 function _ construct ($ Port = NULL) // define the _ Construct Method 69 {70 $ this-> stream = @ socket_create_listen ($ port? $ Port: Port); // open the port to accept connection 71} 72 function isactive () // define isactive method 73 {74 if ($ this-> Stream) // if there is a connection 75 {76 return true; // return the true value 77} 78 else // No connection 79 {80 return false; // return the false value 81} 82}