zoukankan      html  css  js  c++  java
  • swoole 异步非堵塞 server/端 client/端 代码,已经测试完毕。贴代码

    服务器环境  centos7.0  swoole4.3 php7.2 pcre4.8  nginx1.8   php-fpm

    server.php

    <?php 
    
    class Server
    {
        private $serv;
    
        public function __construct() {
    
            $this->serv = new swoole_server("0.0.0.0", 9501);
    
            $this->serv->set(array(
                'worker_num' => 8,
                'daemonize' => false,
                'max_request' => 10000,
                'dispatch_mode' => 2,
                'debug_mode'=> 1
            ));
    
            $this->serv->on('Start', array($this, 'onStart'));
            $this->serv->on('Connect', array($this, 'onConnect'));
            //$this->serv->on('Message', array($this, 'onMessage'));
            $this->serv->on('Receive', array($this, 'onReceive'));
            $this->serv->on('Close', array($this, 'onClose'));
    
            $this->serv->start();
        }
    
        public function onStart( $serv ) {
            echo "Start
    ";
        }
    
        public function onConnect( $serv, $fd, $from_id ) {
            $serv->send( $fd, "收到 {$fd}!" );
        }
    
        // public function onMessage( $serv, $fd, $from_id ) {
        //     $serv->send( $fd, "Hello {$fd}!我已经收到你的信息" );
        // }
    
        public function onReceive( $serv, $fd, $from_id, $data ) {
            echo "Get Message From Client {$fd}:{$data}
    ";
    
            $serv->send( $fd, "Hello {$fd}!我收到了你的信息!{$data}" );
    
        }
    
        public function onClose( $serv, $fd, $from_id ) {
            echo "Client {$fd} close connection
    ";
        }
    }
    // 启动服务器
    $server = new Server();
    
    ?>

    client.php  异步 非阻塞

    <?php
    
    $client = new swoole_client(SWOOLE_TCP | SWOOLE_ASYNC); //异步非阻塞
    
    $client->on("connect", function($cli) {
        $cli->send("hello world
    ");
    });
    
    $client->on("receive", function($cli, $data) {
    
        echo "received: $data
    ";
        //sleep(1);
        fwrite(STDOUT, "请输入消息:");  
                
        $msg = trim(fgets(STDIN));
    
        $cli->send( $msg );
    });
    
    $client->on("close", function($cli){
        echo "closed
    ";
    });
    
    $client->on("error", function($cli){
        exit("error
    ");
    });
    
    $client->connect('0.0.0.0', 9501, 0.5);
    
    
    
    ?>

    测试 结果

          

  • 相关阅读:
    Gengxin讲STL系列——Set
    理解Python的With语句
    Python中Non-ASCII character 'xe7' in file的问题解决
    gnome-terminal的一些调整
    硬盘的CHS寻址
    Wiz发布cnblog笔记
    cygwin安装man手册
    linux命令行使用
    小步前进
    学习的感觉真好
  • 原文地址:https://www.cnblogs.com/heijinli/p/10535781.html
Copyright © 2011-2022 走看看