您的当前位置:首页>全部文章>文章详情

如果使用php作为客户端 链接socket

mini胖发表于:2022-04-07 14:52:30浏览:1539次TAG: #PHP

如果使用php作为客户端 链接socket
本文借助了workerman来实现的,所以小伙伴们需要到workerman的官网下载

composer require workerman/workerman

下面就直接上代码了

<?php


require_once 'vendor/autoload.php';

use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;

$worker = new Worker();

$worker->onWorkerStart = function($worker){

    $con = new AsyncTcpConnection('ws://xxxxxx');
    //数据库需要单独去composer
    global $db;
    $db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'x', 'x', 'x');
    global $count;
    $count = 0;
    $con->onConnect = function($con) {
       //连接成功了就能发信息了
        $send=json_encode([]);
        $con->send($send);
    };


    $con->onMessage = function($con, $data) use ($db) { 
        //当服务端推送数据的时候可以在此回调函
    };

    $con->onClose = function ($con) {
        //这个是延迟断线重连,当服务端那边出现不确定因素,比如宕机,那么相对应的socket客户端这边也链接不上,那么可以吧1改成适当值,则会在多少秒内重新,我也是1,也就是断线1秒重新链接
        $con->reConnect(1);
    };

    $con->onError = function ($connection, $code, $msg) {
        echo "error $code $msg\n";
    };

    $con->connect();
};

Worker::runAll();