php socket Client and Server Application Examples

  • 2021-07-06 10:36:34
  • OfStack

Often there are friends will be php socket application full of doubts, this article on the example code for 1 explanation, hoping to beginner php friends play a 1 point of help

The specific code is as follows:

1. Server-side code:


<?php
class SocketServer{
  private $_port=&#39;9000&#39;;
  private $_address=&#39;127.0.0.1&#39;;
  private $_client_socket_list=array();
  public function __set($name,$val){
    $this--->$name=$val;
  }
  private function _showError($error){
    exit($error);
  }
  /**
   *  Begin socket Server-side listening port 
   */
  public function start(){
    //  Create a port 
    if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) === false) {
      $this->_showError("socket_create() failed :reason:" . socket_strerror ( socket_last_error () ));
    }
    //  Binding 
    if (socket_bind ( $sock, $this->_address, $this->_port ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ));
    }
    //  Eavesdropping 
    if (socket_listen ( $sock, 5 ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ) );
    }
    do {
      // When there is 1 When a client connects 
      if ($client_socket=socket_accept ( $sock )) {
        $count = count ( $this->_client_socket_list ) + 1;
        // Add new users   In the client array 
        $this->_client_socket_list[]=$client_socket;
        echo "new connection:\r\n";// The server side outputs the number of clients currently connected 
        echo "current connection:{$count}\r\n";
        // Accept the string passed by the client 
        $msg=$this->read($client_socket);
        echo "client:{$msg}\r\n";
        // Server passes value to client 
        $my_msg="I am fine,think you\r\n";
        $this->send($client_socket,$my_msg);
      }
      /**
       *  This code is for your reference , Used to judge whether a client actively loses connection 
      else{
        foreach ( $this->_client_socket_list as $socket ) {
          $len = socket_recv ($socket, $buffer, 2048, 0 ); //  Accept 1 Client information under , If is 0 Represents disconnection 
          if ($len < 7) {
            // Written here is to connect the client business 
          }
        }
      }
       */
    }while(true);  
  }
  /**
   *  Send data to the client 
   */
  public function send($client_socket,$str){ 
    return socket_write ( $client_socket,$str, strlen ( $str ) );
  }
  /**
   *  Accept data from the client 
   */
  public function read($client_socket){
    return socket_read ( $client_socket, 8192 );//8192 Acceptance length of actual representative , I use 819292 Indicate length 1 Point , This long 1 The string of dots can also be accepted , Less than 8192 It doesn't matter , Will automatically recognize 
  }
}
$socket_server =new SocketServer();
$socket_server->start();// Start listening 

2. Client code:


<?php
class SocketServer{
  private $_port=&#39;9000&#39;;
  private $_address=&#39;127.0.0.1&#39;;
  private $_client_socket_list=array();
  public function __set($name,$val){
    $this--->$name=$val;
  }
  private function _showError($error){
    exit($error);
  }
  /**
   *  Begin socket Server-side listening port 
   */
  public function start(){
    //  Create a port 
    if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) === false) {
      $this->_showError("socket_create() failed :reason:" . socket_strerror ( socket_last_error () ));
    }
    //  Binding 
    if (socket_bind ( $sock, $this->_address, $this->_port ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ));
    }
    //  Eavesdropping 
    if (socket_listen ( $sock, 5 ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ) );
    }
    do {
      // When there is 1 When a client connects 
      if ($client_socket=socket_accept ( $sock )) {
        $count = count ( $this->_client_socket_list ) + 1;
        // Add new users   In the client array 
        $this->_client_socket_list[]=$client_socket;
        echo "new connection:\r\n";// The server side outputs the number of clients currently connected 
        echo "current connection:{$count}\r\n";
        // Accept the string passed by the client 
        $msg=$this->read($client_socket);
        echo "client:{$msg}\r\n";
        // Server passes value to client 
        $my_msg="I am fine,think you\r\n";
        $this->send($client_socket,$my_msg);
      }
      /**
       *  This code is for your reference , Used to judge whether a client actively loses connection 
      else{
        foreach ( $this->_client_socket_list as $socket ) {
          $len = socket_recv ($socket, $buffer, 2048, 0 ); //  Accept 1 Client information under , If is 0 Represents disconnection 
          if ($len < 7) {
            // Written here is to connect the client business 
          }
        }
      }
       */
    }while(true);  
  }
  /**
   *  Send data to the client 
   */
  public function send($client_socket,$str){ 
    return socket_write ( $client_socket,$str, strlen ( $str ) );
  }
  /**
   *  Accept data from the client 
   */
  public function read($client_socket){
    return socket_read ( $client_socket, 8192 );//8192 Acceptance length of actual representative , I use 819292 Indicate length 1 Point , This long 1 The string of dots can also be accepted , Less than 8192 It doesn't matter , Will automatically recognize 
  }
}
$socket_server =new SocketServer();
$socket_server->start();// Start listening 

Note: Server-side please use CLI mode, cgi mode will time out, this is a novice often like to make mistakes. So what is CLI mode? Simply put, use the command line to execute, and don't use the visitor to open, otherwise it will time out!


Related articles: