1.首先安装 swoole 扩展 Swoole-1.x 需要 PHP-5.3.10 或更高版本 Swoole-2.x 需要 PHP-7.0.0 或更高版本
公司环境是 php5.6.31所以比较麻烦需要编译安装,7以上直接使用命令 (pecl install swoole)
wget https://github.com/swoole/swoole-src/archive/v1.10.1.tar.gz tar -zxvf v1.10.1.tar.gz cd swoole-src-1.10.1 phpize ./configure --with-php-config=/usr/local/php/bin/php-config make && make install
然后在 php.ini 添加 swoole.so 扩展即可 2.使用 laravel 的 artisan 创建命令 php artisan make:command Swoole #创建一个命令 swoole 并会在 app/Console/Commands 增加一个 Swoole.php 的文件
Commands\Swoole::Class #在 Kernel.php 里增加命令列表 3.运行 socket 服务 1.编辑 app/Console/Command 里的 Swoole.php 文件
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Swoole extends Command
{
public $ws;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'swoole {action?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'swoole';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$action = $this->argument('action');
switch ($action) {
case 'close':
break;
default:
$this->start();
break;
}
}
public function start()
{
//创建 websocket 服务器对象,监听 0.0.0.0:9502 端口
$this->ws = new \swoole_websocket_server("0.0.0.0", 9502);
//监听 WebSocket 连接打开事件
$this->ws->on('open', function ($ws, $request) {
var_dump($request->fd . "连接成功");
// $ws->push($request->fd, "hello, welcome\n");
});
//监听 WebSocket 消息事件
$this->ws->on('message', function ($ws, $frame) {
// echo "Message: {$frame->data}\n";
// $ws->push($frame->fd, "server: {$frame->data}");
// var_dump($ws->connection_info($frame->fd));
//fd 绑定客户端传过来的标识 uid
$ws->bind($frame->fd, $frame->data);
});
$this->ws->on('request', function ($request, $response) {
// 接收 http 请求从 post 获取参数
// 获取所有连接的客户端,验证 uid 给指定用户推送消息
// token 验证推送来源,避免恶意访问
if ($request->post['token'] == ### ) {
$clients = $this->ws->getClientList();
$clientId = [];
foreach ($clients as $value) {
$clientInfo = $this->ws->connection_info($value);
if (array_key_exists('uid', $clientInfo) && $clientInfo['uid'] == $request->post['s_id']) {
$clientId[] = $value;
}
}
if (!empty($clientId)) {
foreach ($clientId as $v) {
$this->ws->push($v, $request->post['info']);
}
}
}
});
//监听 WebSocket 连接关闭事件
$this->ws->on('close', function ($ws, $fd) {
echo "client:{$fd} is closed\n";
});
$this->ws->start();
}
}
【注】此处为了结合 app 上传数据时使用 curl 触发 request 回调通知 web 端的实例所以使用了 httpserver 的 onrequest 事件,如果以后有更好的办法去触发服务端实时主动推送。
2.编辑 html
<div id="test">
<a href="javascript:void(0)">运行 websocket</a>
</div>
$('#test').click(function(){
if("WebSocket" in window){
console.log("您的浏览器支持 websocket\n");
var ws = new WebSocket("ws://66.66.66.66:9502");//创建 websocket 对象
ws.onopen = function(){
// ws.send("连接已建立\n");
ws.send($("#content").attr("js-sid"));
console.log("数据发送中");
}
ws.onmessage = function(evt){
var recv_msg = evt.data;
console.log("接受到的数据为:"+recv_msg);
}
ws.onerror = function(evt,e){
console.log("错误信息为"+e);
}
ws.onclose = function(){
console.log("连接已关闭");
}
}else{
console.log("您的浏览器不支持 websocket\n");
}
});
3.curl 方法(调用就行)
public function swooletest($param = ['s_id'=>2, 'info'=>'info'])
{
$param['token'] = ###;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:9502");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
//设置 post 数据
$post_data = $param;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_exec($ch);
curl_close($ch);
}
4.测试的时候直接在 laravel 的 artisan 所在目录使用命令 php artisan swoole 即可启动 socket 服务,然后页面运行客户端,最后调用 curl 推送数据。
4.成功之后
用 supervisor 守护 swoole 命令,或者 nohup 后台启动。
supervisor 配置麻烦不过可以自动重启,nohup 一条命令解决
nohup php artisan swoole & #一条命令解决
此处说明几个问题
1.此处我采用的是 bind 方法,当客户端连接的时候 send 一个 uid 过来,然后在服务端处理的时候把 uid 和 fd 绑定在一起,当你想向某个客户端发送数据时传一个 uid,通过 uid 找到 fd 进行指定发送,但是此处我用的是遍历 getClientList 所有连接用户(方法欠佳)的信息 connection_info 进行判定。希望能改善这种方法
2.因为是 curl 访问 httpserver 的形式,所以为了避免恶意访问,加一个 token 验证。
3.推送的信息转换成 json 再传,即 info 值
4.本实例的账户可能会在多个终端登录,有多个 fd 绑定 uid,所以遍历推送 push
复制代码
阅读原文请访问以下链接 : www.zxb8.cc/?p=515