PHP使用swoole编写简单的echo服务器示例
程序员文章站
2022-10-10 20:38:28
本文实例讲述了php使用swoole编写简单的echo服务器。分享给大家供大家参考,具体如下:server.php代码如下:
本文实例讲述了php使用swoole编写简单的echo服务器。分享给大家供大家参考,具体如下:
server.php代码如下:
<?php class echoserver { protected $serv = null; public function __construct() { $this->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代码如下:
<?php class echoclient { protected $client = null; public function __construct() { //注意这里需设置为异步,不然下面无法设置事件回调函数 $this->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
运行结果如下:
上一篇: 计算两个经纬度点的实际距离
下一篇: PHP 图片合成、仿微信群头像的方法示例