启动TCP服务代码
<?php
/**
* 智慧公厕
*/
namespace Toilet\Action;
class IndexAction extends CommonAction
{
public function server() {
//创建Server对象,监听 127.0.0.1:25111端口
$serv = new \Swoole\Server("127.0.0.1", 25111);
//监听连接进入事件
$serv->on('Connect', function ($serv, $fd) {
echo "Client: Connect.\n";
setlog([$fd],'','连接','toilet.log');
});
//监听数据接收事件
$serv->on('Receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, "Server: ".$data);
setlog([$data,$fd,$from_id],'','响应','toilet.log');
});
//监听连接关闭事件
$serv->on('Close', function ($serv, $fd) {
echo "Client: Close.\n";
setlog([$fd],'','关闭','toilet.log');
});
//启动服务器
$serv->start();
}
}
执行
# php toilet.php Index/server
PHP Fatal error: Class 'Swoole\Server' not found in /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php on line 12
Fatal error: Class 'Swoole\Server' not found in /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php on line 12
Class 'Swoole\Server' not found
FILE: /home/wwwroot/default/smart/smart-community/Application/Toilet/Action/IndexAction.class.php(12)
报错了,因为swoole没有安装
安装swoole后
# php toilet.php Index/server
Client: Connect.
客户端测试
# telnet 127.0.0.1 25111
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hello
Server: hello