欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

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

时间:2021-05-28 08:03:08|栏目: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相关内容感兴趣的读者可查看本站专题:《PHP网络编程技巧总结》、《php socket用法总结》、《php面向对象程序设计入门教程》、《PHP数据结构与算法教程》及《php程序设计算法总结

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

上一篇:php面向对象全攻略 (七) 继承性

栏    目:PHP代码

下一篇:PHP实时显示输出

本文标题:PHP使用swoole编写简单的echo服务器示例

本文地址:http://www.codeinn.net/misctech/130793.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有