php websocket

php websocket项目开发,推荐使用:Workerman

本片内容使用Workerman实现了简单的及时聊天功能,具体代码如下:

<?php 
// phpinfo();
header('Content-Type: text/html; charset=utf-8');

require 'vendor/autoload.php';

use Workerman\Worker;

$sk=new Sock();
 
//对创建的socket循环进行监听,处理数据
$sk->run();

function array_remove($arr, $key){ 
  if(!array_key_exists($key, $arr)){ 
    return $arr; 
  } 
  $keys = array_keys($arr); 
  $index = array_search($key, $keys); 
  if($index !== FALSE){ 
    array_splice($arr, $index, 1); 
  } 
  return $arr; 
 
} 

class Sock{
    public $sockets; //socket的连接池,即client连接进来的socket标志
    public $ws_worker;
     
    public function __construct(){
 
        // Create a Websocket server
        $this->ws_worker = new Worker("websocket://0.0.0.0:8889");

        // 4 processes
        $this->ws_worker->count = 4;

        // Emitted when new connection come
        $this->ws_worker->onConnect = function($connection)
        {
            echo "New connection\n";
            echo 'id=' . $connection->id . '    ';
            $this->sockets[$connection->id] = array('client'=>$connection);
            echo 'count=' . count($this->sockets) . '    ';

        };

        // Emitted when data received
        $this->ws_worker->onMessage = function($connection, $data)
        {
            // Send hello $data
            echo "\n".$connection->id." -> req: ".$data;
            $jdata = json_decode($data,true);
            echo "\n op: ".$jdata['op'];
            if($jdata['op'] == 'login'){
                //{'op':'login','user':user}
                $cs = $this->sockets[$connection->id];
                $cs['user'] = $jdata['user'];
                $this->sockets[$connection->id] = $cs;
                $connection->send($jdata['user'].'登录成功'); 
                return;
            }else{
                // {'op':'chat','from_user':user,'to_user':user,'msg':msg}
                $deal = false;
                if($jdata['op'] == 'chat'){
                    foreach ($this->sockets as $key => $value) {
                        if($value['user'] == $jdata['to_user']){
                            $value['client']->send($jdata['msg']);
                            $connection->send($data);
                            $deal = true;
                        }
                    }
                    if($deal == false){
                        $connection->send($jdata['user'].'会员不存在');
                    }
                }else{
                    $connection->send('参数异常: ' . $data);                
                }    
            }

            
        };

        // Emitted when connection closed
        $this->ws_worker->onClose = function($connection)
        {
            echo "Connection closed\n";
            $this->sockets = array_remove($this->sockets, $connection->id);
        };
    }
     
    public function run(){
        Worker::runAll();        
    }
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jquery.js" type="text/javascript"></script>

</head>
<body>
    <input type="text" id="input" placeholder="Message…" />
    <hr />
    <pre id="output"></pre>
    
    <script>
      var user = '';
      var host   = 'ws://127.0.0.1:8889';
      var socket = null;
      var input  = document.getElementById('input');
      var output = document.getElementById('output');
      var print  = function (message) {
          var samp       = document.createElement('samp');
          samp.innerHTML = message + '\n';
          output.appendChild(samp);
    
          return;
      };

      user = window.prompt("欢迎?","请在此输入您的姓名。");
    
      input.addEventListener('keyup', function (evt) {
          if (13 === evt.keyCode) {
              var msg = input.value;
    
              if (!msg) {
                  return;
              }
    
              try {
                  socket.send(msg);
                  input.value = '';
                  input.focus();
              } catch (e) {
                  console.log(e);
              }
    
              return;
          }
      });
    
      try {
          socket = new WebSocket(host);
          socket.onopen = function () {
              print('connection is opened');
              input.focus();
              socket.send('{"op":"login","user":"'+user+'"}');
              return;
          };
          socket.onmessage = function (msg) {
              print(msg.data);
    
              return;
          };
          socket.onclose = function () {
              print('connection is closed');
    
              return;
          };

      } catch (e) {
          console.log(e);
      }
    </script>
</body>
</html>

 

使用 php socket.php 启动服务端。

js端要发起json结构的数据,如下截图:

 

posted @ 2018-05-05 20:23  scott_j  阅读(140)  评论(0编辑  收藏  举报