tp6 workerman

首先composer

composer require topthink/think-worker

\config\worker_server.php

return [
    // 扩展自身需要的配置
    'protocol'       => 'websocket', // 协议 支持 tcp udp unix http websocket text
    'host'           => '0.0.0.0', // 监听地址
    'port'           => 2346, // 监听端口
//    'socket'         => 'http://127.0.0.1:2346', // 完整监听地址
    'socket'         => '', // 完整监听地址
    'context'        => [], // socket 上下文选项
    'worker_class'   => 'app\http\Worker', // 自定义Workerman服务类名 支持数组定义多个服务

去宝塔和云服务器开启2346端口

新建文件夹app\http  创建Woker类

<?php

namespace app\http;

use think\exception\ValidateException;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\facade\Db;
use GatewayWorker\Lib\Gateway;

class Worker extends Server {

    protected $socket = 'websocket://0.0.0.0:2346';
    protected $uidConnections = array();

    public function __construct() {
        parent::__construct();
//        $this->onWorkerStart();
    }
    
//    public function onWorkerStart( $Worker ) {
//        //
//    }
    
    
    public function add_timer(){
        #设置每60秒执行一次定时任务
        /**
         *前端启动方式:
        // 假设服务端ip为127.0.0.1
        ws = new WebSocket("ws://127.0.0.1:2347");
        ws.onopen = function() {
        alert("连接成功");
        };
        ws.onmessage = function(e) {
        alert("收到服务端的消息:" + e.data);
        };
         */
    }
    
    
    public function onConnect($connection) {
        $message = [
            'app' => 'test',
            'yourId' => $connection->id,
        ];
        $connection->send(json_encode($message,JSON_UNESCAPED_UNICODE));
    }
    
    
    /**
     * @param $connection
     * @param $data 142842567084ds
     */
    public function onMessage($connection,$data) {
        $message = [
            'data' => $data,
            'yourId' => $connection->id,
        ];
        $connection->send(json_encode($message,JSON_UNESCAPED_UNICODE));

    }
    
    
    public function sendMsg( $content ) {
        if( isset( $content['type'] ) ) {
            $type = $content['type'];
            $sendId = $content['sendId'];

            if( $type == "pushSingle" ) {
                Gateway::sendToUid( $sendId, $content['content'] );
            }
        }
    }
    
}

启动命令

php think worker:server

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值