Pay attention to

  1. IP addresses cannot be true loopback addresses such as 127.0.0.1 during socket_bind

  2. PHP > /var/tmp/a.log2 > &1&nohup PHP server. PHP > /var/tmp/a.log2 > &1&

1: UDP mode

1) server.php


     
  1. <? php

  2. //error_reporting( E_ALL );

  3. set_time_limit( 0 );

  4. ob_implicit_flush();

  5. $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );

  6. if ( $socket === false ) {

  7.  echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n";

  8. }

  9. $ok = socket_bind($socket, '202.85.218.133', 11109);

  10. if ( $ok === false ) {

  11.  echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );

  12. }

  13. while ( true ) {

  14.  $from = "";

  15.  $port = 0;

  16.  socket_recvfrom( $socket, $buf,1024, 0, $from, $port );

  17.  echo $buf;

  18.  usleep( 1000 );

  19. }

  20. ? >

Copy the code

2) client.php


     
  1. <? php

  2. $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

  3. $msg = 'hello';

  4. $len = strlen($msg);

  5. Socket_sendto ($sock, $MSG, $len, 0, '202.85.218.133', 11109);

  6. socket_close($sock);

  7. ? >

Copy the code

Two: TCP

1)server.php


     
  1. <? php

  2. //error_reporting( E_ALL );

  3. set_time_limit( 0 );

  4. ob_implicit_flush();

  5. $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );

  6. Socket_bind ($socket, '192.168.2.143', 11109);

  7. socket_listen($socket);

  8. $acpt=socket_accept($socket);

  9. echo "Acpt! \n";

  10. while ( $acpt ) {

  11.  $words=fgets(STDIN);

  12.  socket_write($acpt,$words);

  13.  $hear=socket_read($acpt,1024);

  14.  echo $hear;

  15.  if("bye\r\n"==$hear){

  16.    socket_shutdown($acpt);

  17.    break;

  18.  }

  19.  usleep( 1000 );

  20. }

  21. socket_close($socket)

  22. ? >

Copy the code

2) client.php


     
  1. <? php

  2. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

  3. $con = socket_connect ($sockets, '192.168.2.143, 11109);

  4. if(! $con){socket_close($socket); exit; }

  5. echo "Link\n";

  6. while($con){

  7.    $hear=socket_read($socket,1024);

  8.    echo $hear;

  9.    $words=fgets(STDIN);

  10.    socket_write($socket,$words);

  11. if($words=="bye\r\n"){break; }

  12. }

  13. socket_shutdown($socket);

  14. socket_close($sock);

  15. ? >

Copy the code

Stay tuned for more sharing