php的echo的例子,PHP使用swoole编写简单的echo服务器示例

本文实例讲述了PHP使用swoole编写简单的echo服务器。分享给大家供大家参考,具体如下:

server.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代码如下:

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

运行结果如下:

4bd0b50a769d36dc73c6eb1fd80dc530.png

4fdf0626544f3eeacddeb101ba8f65c3.png

希望本文所述对大家PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值