thinkphp5使用Workerman啟動udp服務

weixin_34019929發表於2017-08-08
1. 安裝(composer)
composer require topthink/think-worker

如果是在window下還需要安裝workerman/workerman-for-win
(然後刪掉vendor\workerman\workerman)

composer require workerman/workerman-for-win
2. 新增啟動檔案在tp5根目錄server.php內容如下
<?php
/**
 * Created by PhpStorm.
 * User: pandeng
 * Date: 2017-08-07
 * Time: 10:50
 */
define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE','index/Worker');
// 載入框架引導檔案
require __DIR__ . '/thinkphp/start.php';

新增服務處理類在controller下建立\index\controller\Worker.php 程式碼如下

<?php

namespace app\index\controller;

use think\worker\Server;

class Worker extends Server
{
    protected $socket = 'udp://0.0.0.0:2346';
    /**
     * 收到資訊
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        echo $data;
        $connection->send($data);
    }

    /**
     * 當客戶端的連線上發生錯誤時觸發
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每個程式啟動
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        echo "onWorkerStart___";
    }
}

3. 新增.pid檔案(啟動時候報錯file_get_contents(/data/project/tp5project/vendor/workerman/workerman/../_data_project_tp5project_server.php.pid): 需要操作此步驟)

在centos7下啟動服務的時候沒有自動建立.pid檔案,固需要手動新增這個空檔案
/data/project/tp5project/vendor/workerman/_data_project_bomei_server.php.pid

4. 修改php.ini(啟動時報錯:stream_socket_server() has been disabled for security reasons需要修改)

/usr/local/php/etc/php.ini
找到disable_functions 這行去掉stream_socket_server

disable_functions = passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status,popen,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru
5. 新增udp所需埠
firewall-cmd --zone=public --add-port=2346/udp --permanent
firewall-cmd --reload

如果用的阿里雲伺服器需要在安全策略新增開放2346埠

1702706-9ee1e03a4215d37b.png
6. 啟動
php server.php start
1702706-c91f10b9b5e58c30.png

相關文章