本篇文章小编给大家分享一下PHP使用swoole编写简单的echo服务器代码示例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
server.php代码如下:
serv = new swoole_server('0.0.0.0', 8888); //配置参数 $this->serv->set(array( 'worker_num' => 4, 'daemonize' => 0, )); //注册回调函数 $this->serv->on('start', array($this, 'start')); $this->serv->on('connect', array($this, 'connect')); $this->serv->on('receive', array($this, 'receive')); $this->serv->on('close', array($this, 'close')); //启动服务 $this->serv->start(); } public function start($serv) { echo "start n"; } //有客户端连接时 public function connect($serv, $fd) { echo "connect n"; $serv->send($fd, "hello n"); } public function close($serv, $fd) { echo "close n"; } public function receive($serv, $fd, $from_id, $data) { echo "get message {$fd} : {$data} n"; //向客户端发送信息 $serv->send($fd, $data . "n"); } } $serv = new EchoServer();
client.php代码如下:
client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $this->client->on('connect', array($this, 'connect')); $this->client->on('receive', array($this, 'receive')); $this->client->on('close', array($this, 'close')); $this->client->on('error', array($this, 'error')); //连接服务端 $this->client->connect('0.0.0.0', 8888); } public function connect($client) { echo "connect n"; } public function receive($client, $data) { echo "server send: {$data}"; //向标准输出写入数据 fwrite(STDOUT, "请输入消息:"); //获取标准输入数据 $msg = trim(fgets(STDIN)); //向服务端发送数据 $client->send($msg); } public function close($client) { echo "close n"; } public function error($client) { echo "error n"; } } $cli = new EchoClient();
然后分别运行这两个脚本
> /data/php56/bin/php server.php > /data/php56/bin/php client.php
运行结果如下:
敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载像素火影骨架佐助 (Perseverance Fire Shadow)手机版v1.16
下载要塞英雄 安卓版v33.20.0-39082670-Android
下载梦想城镇vivo最新版本 安卓版v12.0.1
梦想城镇vivo版是这款卡通风模拟经营类手游的渠道服版本,玩
怦然心动的瞬间 安卓版v1.0
怦然心动的瞬间是一款真人向的恋爱互动游戏,在游戏中玩家将扮演
曼尼汉堡店游戏 安卓版v1.0.3
曼尼汉堡店是一款非常好玩的精品恐怖类型冒险游戏,在这款游戏中
现代总统模拟器去广告版 安卓版v1.0.46
现代总统模拟器是一款休闲养成类游戏,可能对于不少的玩家来说都
现代总统模拟器付费完整版 安卓版v1.0.46
现代总统模拟器高级版在商店是需要付费的,相对于普通版本,高级