因项目只做socket客户端,不想用workerman或者swoole框架,简单实现ws PHP客户端

php 复制代码
D:\phpstudy_pro\Extensions\php\php7.4.3nts\composer require textalk/websocket
1、因项目只做socket客户端,不想用workerman或者swoole框架,简单实现ws PHP客户端
<?php
use WebSocket\Client as WsClient;

 private static $worker = null;
 
 public static function getClinet($url) {
        if (self::$worker == null) {
            self::$worker = new WsClient($url);
        }

        try {
            self::$worker->ping();
        } catch (\Exception $e) {
            self::$worker = null;
            return null;
        }

        return self::$worker;
    }
	
	public function sendToWorkerByWebSocket($taskModel) {
        $data = [
            'id' => $taskModel->id,
            'inst' => $taskModel->inst,
        ];
        $jsonData = json_encode($data);

        $url = sprintf('ws://%s:%d/ws', env('TCPWORKER_IP', '127.0.0.1'), env('TCPWORKER_PORT', 6));

        $client = self::getClinet($url);
        if ($client) {
            try {
                $client->send($jsonData);
                // $res = $client->receive();
                \Log::channel('websocket')->info('success:' .$jsonData);
            } catch (\Exception $e) {
                \Log::channel('websocket')->info($e->getMessage());
                \Log::channel('websocket')->info('fail:' .$jsonData);
            }
        } else {
            \Log::channel('websocket')->info('fail:ping不通');
        }

        return true;
    }

docs/Client.md · master · mirrors / Textalk / websocket-php · GitCode

相关推荐
damoluomu6 天前
挑 PHP CMS 之前,先学会看它的协议
php
子非鱼a6 天前
【WEB】Online ToolWEB
php
PHP实战开发录6 天前
Nginx上传大文件为什么报413
nginx·php·开发
damoluomu7 天前
国产企业级 PHP CMS:哪些能免费商用
php
郑州光合科技余经理7 天前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
MyFreeIT7 天前
Android PHP Manual
php
aixingpan7 天前
aixingpan.cn API开发文档:api_docs_trichart_natal_progression_sec_transit2接口指南
前端·php
sbjdhjd7 天前
从日志包含到临时文件竞争:文件包含进阶复盘中的 Docker、Windows 与 Session 限制
网络·安全·web安全·网络安全·数据挖掘·php·rce
daxiangxm7 天前
【趣味休息】“围住小猫在线玩”-“困住小猫”,又回来了
数据结构·人工智能·vscode·github·php
星光开发者7 天前
基于Spring Boot的充电桩管理系统的设计与实现-计算机毕设【课程设计】57105
vue.js·spring boot·vscode·mysql·django·php·express