Swoole集成到控制台 [ 2.0 版本 ]
Swoole的安装我就不说了,百度上可以查到很多,直接进入主题
console\controllers 目录下新建SwooleController.php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class SwooleController extends Controller {
private $serv;
public function __construct() {
$this->serv = new \swoole_server("192.168.85.132", 9502);
$this->serv->set(array(
'worker_num' => 8,
'daemonize' => false,
'max_request' => 10000,
'dispatch_mode' => 2,
'debug_mode'=> 1
));
$this->serv->on('Start', array($this, 'onStart'));
$this->serv->on('Connect', array($this, 'onConnect'));
$this->serv->on('Receive', array($this, 'onReceive'));
$this->serv->on('Close', array($this, 'onClose'));
$this->serv->start();
}
public function onStart( $serv ) {
echo "Start\n";
}
public function onConnect( $serv, $fd, $from_id ) {
$serv->send( $fd, "Hello {$fd}!" );
}
public function onReceive( \swoole_server $serv, $fd, $from_id, $data ) {
echo "Get Message From Client {$fd}:{$data}\n";
}
public function onClose( $serv, $fd, $from_id ) {
echo "Client {$fd} close connection\n";
}
}
LINUX服务器下运行 php yii Swoole
根目录下新建 helpers文件夹
common\config\bootstrap.php 添加一行
Yii::setAlias('@helpers', dirname(dirname(__DIR__)) . '/helpers');
helpers文件夹新建Client.php
代码如下:
namespace helpers;
class Client
{
private $client;
public function __construct() {
$this->client = new \swoole_client(SWOOLE_SOCK_TCP);
}
public function connect() {
if( !$this->client->connect("192.168.85.132", 9502 , 1) ) {
echo "Error: \n";
}
$message = $this->client->recv();
echo "Get Message From Server:{$message}\n";
// fwrite(STDOUT, "请输入消息:");
// $msg = trim(fgets(STDIN));
$this->client->send( $message );
}
}
backend\controllers 下新建文件ClientController.php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use helpers\Client;
class ClientController extends Controller
{
public function actionIndex(){
$client = new Client();
$client->connect();
}
}
telnet 192.168.85.132 9502
可以进行测试
成功显示:
Trying 192.168.85.132...
Connected to 192.168.85.132.
Escape character is '^]'.
失败显示:
Trying 192.168.85.132...
telnet: connect to address 192.168.85.132: Connection refused
写到这里吧,有问题及时讨论
httpp886
注册时间:2017-01-12
最后登录:2017-11-09
在线时长:16小时47分
最后登录:2017-11-09
在线时长:16小时47分
- 粉丝15
- 金钱1275
- 威望60
- 积分2035
共 7 条评论
你这种压根就不算扩展啊。只是类似引用autoload差不多。
亲,人家没有说是拓展
标题写的很清楚,
也不错 赞一个
helpers 在那个目录下啊
根目录新建的
学习了学习了
你好,请教“Class 'swoole_client' not found” 这种情况,不允许在fpm下 new client对象,这个怎么办呢?在cli下直接php a.php 是可以的,用fpm+网站访问,我按照你上边写的不执行
你好楼主出现这种情况是什么原因,Error: Connection refused[111].
这样 指定ip 端口后,如果我是部署在多台机器上呢,不好搞吧
第二个里面 定义别名,有啥用呢