httpp886 2017-04-01 13:49:23 2098次浏览 4条评论 8 1 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

写到这里吧,有问题及时讨论

gii
您需要登录后才可以评论。登录 | 立即注册
在线
788