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);
    
    
    
    ?>

    测试 结果

          

  • 相关阅读:
    给右键 添加dos命令
    js模拟系统无刷新跳回登录页1
    MBProgressHUD.h file not found
    建立个人博客网站
    <转>提高iOS开发效率的方法和工具
    设置模块功能设计思路及代码实现
    经验之谈
    'NSInteger' (aka 'long') to 'int32
    OCR技术
    升级Xcode6.4插件失效解决办法
  • 原文地址:https://www.cnblogs.com/heijinli/p/10535781.html
Copyright © 2011-2022 走看看