服务器环境 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); ?>
测试 结果