怎么在PHP中使用swoole编写一个echo服务器-创新互联

怎么在PHP中使用swoole编写一个echo服务器?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联主营宜州网站建设的网络公司,主营网站建设方案,app软件开发公司,宜州h5微信平台小程序开发搭建,宜州网站营销推广欢迎宜州等地区企业咨询

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中使用swoole编写一个echo服务器

怎么在PHP中使用swoole编写一个echo服务器

看完上述内容,你们掌握怎么在PHP中使用swoole编写一个echo服务器的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!

文章名称:怎么在PHP中使用swoole编写一个echo服务器-创新互联
分享URL:https://www.cdcxhl.com/article18/phsgp.html

成都网站建设公司_创新互联,为您提供定制开发网站策划自适应网站网站导航小程序开发网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站托管运营