Home  >  Article  >  Backend Development  >  Basic principles of php socket|server server.php|client client.php

Basic principles of php socket|server server.php|client client.php

WBOY
WBOYOriginal
2016-07-25 08:47:421073browse
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~~~
  1. Server.php
  2. $host = '192.168.0.10';
  3. $port = 88888;
  4. if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
  5. echo " socket create success.n";
  6. }
  7. if($bind = socket_bind($socket, $host, $port)){
  8. echo "socket bind success.n";
  9. }
  10. if($listen = socket_listen( $socket)){
  11. echo "socket listening...n";
  12. }
  13. if($connect = socket_accept($socket)){
  14. echo "socket accept a connect success.n";
  15. }
  16. // ================================================== =//
  17. socket_write($connect, 'I am from Server.php at DateTime:'.date('Y-m-d H:i:s')."n");
  18. //========= ===========Send to client==================================== ===============//
  19. //============================== =====================//
  20. $read = socket_read($connect, 1024);
  21. echo $read;
  22. //======= =====Accept messages from the client============================///
  23. //while($connect = socket_accept($socket)){
  24. // $read = socket_read($connect, 1024);
  25. // echo $read;
  26. //}
  27. //Loop accept
Copy code
  1. Client.php
  2. $host = '192.168.0.10';
  3. $port = 88888;
  4. if($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)){
  5. echo " socket create success.n";
  6. }
  7. socket_connect($socket, $host, $port);
  8. //======================== ===============================//
  9. socket_write($socket, 'I am from client.php at DateTime:' .date('Y-m-d H:i:s')."n");
  10. //==================Send a request to the server====== ==========================================//
  11. //== ================================================== ===//
  12. $read = socket_read($socket, 1024);
  13. echo $read;
  14. //================Accept the return data from the server====== ===================//
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn