• 技术文章 >php教程 >php手册

    Swoole 初识 - wangyulu

    2016-05-20 11:54:33原创544
    官方定义:

    Swoole:重新定义PHP

    PHP的异步、并行、高性能网络通信引擎,使用纯C语言编写,提供了PHP语言的异步多线程服务器,异步TCP/UDP网络客户端,异步MySQL,异步Redis,数据库连接池,AsyncTask,消息队列,毫秒定时器,异步文件读写,异步DNS查询。 Swoole内置了Http/WebSocket服务器端/客户端、Http2.0服务器端。
    Swoole可以广泛应用于互联网、移动通信、企业软件、云计算、网络游戏、物联网、车联网、智能家居等领域。 使用PHP+Swoole作为网络通信框架,可以使企业IT研发团队的效率大大提升,更加专注于开发创新产品。

    swoole 扩展安装及案例来源:http://wiki.swoole.com/wiki/page/6.html

    简单案例:

    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('Receive', array($this, 'onReceive'));
            $this->serv->on('Close', array($this, 'onClose'));
    
            $this->serv->start();
        }
    
        public function onStart($serv)
        {
            echo "Start\n";
        }
    
        public function onConnect($serv, $fd, $from_id)
        {
            $serv->send($fd, "Hello {$fd}!");
        }
    
        public function onReceive(swoole_server $serv, $fd, $from_id, $data)
        {
            echo "Get Message From Client {$fd}:{$data}\n";
        }
    
        public function onClose($serv, $fd, $from_id)
        {
            echo "Client {$fd} close connection\n";
        }
    
    }
    
    // 启动服务器
    $server = new Server();

    php
    
    class Client
    {
    
        private $client;
    
        public function __construct()
        {
            $this->client = new swoole_client(SWOOLE_SOCK_TCP);
        }
    
        public function connect()
        {
            if (!$this->client->connect("127.0.0.1", 9501, 1)) {
                echo "Error: {$fp->errMsg}[{$fp->errCode}]\n";
            }
            $message = $this->client->recv();
            echo "Get Message From Server:{$message}\n";
    
            fwrite(STDOUT, "请输入消息:");
            $msg = trim(fgets(STDIN));
            $this->client->send($msg);
        }
    
    }
    
    $client = new Client();
    $client->connect();

    分别打开两个终端输入:php server.php  php client.php 即可看到效果!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:Swoole 初识 - wangyulu
    上一篇:消息系统设计与实现 - 珩~ 下一篇:DZ 3.2 URL 伪静态配置 教程 - shuijilove
    线上培训班

    相关文章推荐

    • 最完整PHP常用工具类大全,• php检查字符串中是否有外链的方法,php字符串• 两千行代码的PHP学习笔记汇总,两千行php学习笔记• 一款php批量生成缩略图代码• 【原】使用wsdl的注意事项

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网