Home > Backend Development > PHP Tutorial > PHP socket client and server application examples_PHP tutorial

PHP socket client and server application examples_PHP tutorial

WBOY
Release: 2016-07-13 10:26:36
Original
920 people have browsed it

Friends often have doubts about the socket application of PHP. This article will explain it with example code, hoping to be helpful to friends who are new to PHP

The specific code is as follows:

1. Server-side code:

<&#63;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);
  }
  /**
   * 开始进行socket服务器端监听端口
   */
  public function start(){
    // 创建端口
    if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) === false) {
      $this->_showError("socket_create() failed :reason:" . socket_strerror ( socket_last_error () ));
    }
    // 绑定
    if (socket_bind ( $sock, $this->_address, $this->_port ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ));
    }
    // 监听
    if (socket_listen ( $sock, 5 ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ) );
    }
    do {
      //当有一个客户端连接的时候
      if ($client_socket=socket_accept ( $sock )) {
        $count = count ( $this->_client_socket_list ) + 1;
        //把新来的用户加入 客户端数组里
        $this->_client_socket_list[]=$client_socket;
        echo "new connection:\r\n";//服务器端输出当前正在连接的客户端数量
        echo "current connection:{$count}\r\n";
        //接受客户端传过来的字符串
        $msg=$this->read($client_socket);
        echo "client:{$msg}\r\n";
        //服务器向客户端传值
        $my_msg="I am fine,think you\r\n";
        $this->send($client_socket,$my_msg);
      }
      /**
       * 这段代码给你参考,用来判断是否有客户端主动失去连接
      else{
        foreach ( $this->_client_socket_list as $socket ) {
          $len = socket_recv ($socket, $buffer, 2048, 0 ); // 接受一下客户端信息,如果为0代表断开连接
          if ($len < 7) {
            //这里写是去连接的客户端业务
          }
        }
      }
       */
    }while(true);  
  }
  /**
   * 发送数据给客户端
   */
  public function send($client_socket,$str){ 
    return socket_write ( $client_socket,$str, strlen ( $str ) );
  }
  /**
   * 从客户端接受数据
   */
  public function read($client_socket){
    return socket_read ( $client_socket, 8192 );//8192实际代表的接受长度,我用819292表示长一点,这样长一点的字符串也可以接受到,不到8192也没关系,会自动识别
  }
}
$socket_server =new SocketServer();
$socket_server->start();//开始监听

Copy after login

2. Client code:

<&#63;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);
  }
  /**
   * 开始进行socket服务器端监听端口
   */
  public function start(){
    // 创建端口
    if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) === false) {
      $this->_showError("socket_create() failed :reason:" . socket_strerror ( socket_last_error () ));
    }
    // 绑定
    if (socket_bind ( $sock, $this->_address, $this->_port ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ));
    }
    // 监听
    if (socket_listen ( $sock, 5 ) === false) {
      $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ) );
    }
    do {
      //当有一个客户端连接的时候
      if ($client_socket=socket_accept ( $sock )) {
        $count = count ( $this->_client_socket_list ) + 1;
        //把新来的用户加入 客户端数组里
        $this->_client_socket_list[]=$client_socket;
        echo "new connection:\r\n";//服务器端输出当前正在连接的客户端数量
        echo "current connection:{$count}\r\n";
        //接受客户端传过来的字符串
        $msg=$this->read($client_socket);
        echo "client:{$msg}\r\n";
        //服务器向客户端传值
        $my_msg="I am fine,think you\r\n";
        $this->send($client_socket,$my_msg);
      }
      /**
       * 这段代码给你参考,用来判断是否有客户端主动失去连接
      else{
        foreach ( $this->_client_socket_list as $socket ) {
          $len = socket_recv ($socket, $buffer, 2048, 0 ); // 接受一下客户端信息,如果为0代表断开连接
          if ($len < 7) {
            //这里写是去连接的客户端业务
          }
        }
      }
       */
    }while(true);  
  }
  /**
   * 发送数据给客户端
   */
  public function send($client_socket,$str){ 
    return socket_write ( $client_socket,$str, strlen ( $str ) );
  }
  /**
   * 从客户端接受数据
   */
  public function read($client_socket){
    return socket_read ( $client_socket, 8192 );//8192实际代表的接受长度,我用819292表示长一点,这样长一点的字符串也可以接受到,不到8192也没关系,会自动识别
  }
}
$socket_server =new SocketServer();
$socket_server->start();//开始监听
Copy after login

Note: Please run the server in CLI mode. The cgi mode will time out. This is a common mistake that novices often make. So what is CLI mode? To put it simply, use the command line to execute it, rather than opening it with a browser, otherwise it will time out!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824620.htmlTechArticleFriends often have doubts about the socket application of php. This article will explain it with example code. I hope it can help Friends who are new to PHP will be a little helpful. The specific code is as follows: 1. Server side...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template