• swooleTCP


    1:先创建服务端文件

    TCP.php

    <?php
    
    class TCP
    {
    private $server = null;
    
    public function __construct(){
    $this -> server = new Swoole\Server('127.0.0.1', 9501);
    $this -> server -> set([
    "worker_num" => 4,
    "max_request" => 50,
    ]);
    $this -> server -> on('Connect', [$this, "onConnect"]);
    $this -> server -> on('Receive', [$this, "onReceive"]);
    $this -> server -> on('Close', [$this, "onClose"]);
    $this -> server -> start();
    }
    /**
    * $fd 客户端链进来的id:0/开始增长
    *
    */
    public function onConnect($server, $fd){
    echo "客户端id: {$fd}链接.\n";
    }
    
    public function onReceive($server, $fd, $reactor_id, $data){
    $server->send($fd, "发送的数据: {$data}");
    }
    
    public function onClose($server, $fd){
    echo "客户端id: {$fd}关闭.\n";
    }
    }
    
    new TCP();

    2:创建客户端文件 TCP.php 

    <?php
    
    // use Swoole\Coroutine\Client;
    // use function Swoole\Coroutine\run;
    
    go(function () {
        $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
        if (!$client->connect('127.0.0.1', 9501, 0.5))
        {
            echo "connect failed. Error: {$client->errCode}\n";
        }
        // fwrite(STDOUT,"请输入:");
        // $res = fgetc(STDIN);
        // $client->send($res);
        $client->send("你好!");
        echo $client->recv();
        $client->close();
    });

    3:打开两个终端执行服务端文件跟客户端文件php TCP.php 回车,就建立成功了

  • 相关阅读:
    【BZOJ】1552/3506 [Cerc2007]robotic sort
    【BZOJ】1014 [JSOI2008]火星人prefix
    【BZOJ】1500: [NOI2005]维修数列
    【51NOD-0】1046 A^B Mod C
    【51NOD-0】1019 逆序数
    【51NOD-0】1018 排序
    【51NOD-0】1012 最小公倍数LCM
    The Grove(poj 3182)
    Iahub and Permutations(codeforces 314c)
    多边形之战(bzoj 2927)
  • 原文地址:https://www.cnblogs.com/sunny20/p/15632046.html
Copyright © 2020-2023  润新知