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

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

server.php代码如下:

<?php
classEchoServer{
protected$serv=null;

publicfunction__construct(){
$this->serv=newswoole_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();
}

publicfunctionstart($serv){
echo"start\n";
}

//有客户端连接时
publicfunctionconnect($serv,$fd){
echo"connect\n";
$serv->send($fd,"hello\n");
}

publicfunctionclose($serv,$fd){
echo"close\n";
}

publicfunctionreceive($serv,$fd,$from_id,$data){
echo"getmessage{$fd}:{$data}\n";
//向客户端发送信息
$serv->send($fd,$data."\n");
}
}

$serv=newEchoServer();

client.php代码如下:

<?php
classEchoClient{
protected$client=null;

publicfunction__construct(){
//注意这里需设置为异步,不然下面无法设置事件回调函数
$this->client=newswoole_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);
}

publicfunctionconnect($client){
echo"connect\n";
}

publicfunctionreceive($client,$data){
echo"serversend:{$data}";

//向标准输出写入数据
fwrite(STDOUT,"请输入消息:");
//获取标准输入数据
$msg=trim(fgets(STDIN));
//向服务端发送数据
$client->send($msg);
}

publicfunctionclose($client){
echo"close\n";
}

publicfunctionerror($client){
echo"error\n";
}
}

$cli=newEchoClient();

然后分别运行这两个脚本

>/data/php56/bin/phpserver.php
>/data/php56/bin/phpclient.php

运行结果如下:

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

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

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

发布于 2021-03-21 22:38:59
收藏
分享
海报
0 条评论
170
上一篇:怎么在Spring Boot中使用webflux 下一篇:怎么在PHP中使用process模块创建子进程
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码