Basic principles and basic usage of php socket: Server: Create a socket=》Bind this socket to the specified IP and port=》Listen to all link requests of this socket=》Respond or return data Client :Create a socket socket=》Connect the socket that needs to be requested=》Send data to the socket=》Read the response data of the socket
(~_~) Please correct any inappropriate understanding~~~
- Server.php
-
-
-
- $host = '192.168.0.10';
- $port = 88888;
-
- if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
- echo " socket create success.n";
- }
-
- if($bind = socket_bind($socket, $host, $port)){
- echo "socket bind success.n";
- }
-
- if($listen = socket_listen( $socket)){
- echo "socket listening...n";
- }
-
- if($connect = socket_accept($socket)){
- echo "socket accept a connect success.n";
- }
-
- // ================================================== =//
- socket_write($connect, 'I am from Server.php at DateTime:'.date('Y-m-d H:i:s')."n");
- //========= ===========Send to client==================================== ===============//
-
- //============================== =====================//
- $read = socket_read($connect, 1024);
- echo $read;
- //======= =====Accept messages from the client============================///
-
-
- //while($connect = socket_accept($socket)){
- // $read = socket_read($connect, 1024);
- // echo $read;
- //}
- //Loop accept
-
Copy code
- Client.php
-
-
-
- $host = '192.168.0.10';
- $port = 88888;
-
- if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
- echo " socket create success.n";
- }
- socket_connect($socket, $host, $port);
-
- //======================== ===============================//
- socket_write($socket, 'I am from client.php at DateTime:' .date('Y-m-d H:i:s')."n");
- //==================Send a request to the server====== ==========================================//
-
- //== ================================================== ===//
- $read = socket_read($socket, 1024);
- echo $read;
- //================Accept the return data from the server====== ===================//
-
Copy code
|