-
Notifications
You must be signed in to change notification settings - Fork 26
SwooleServer
李铭昕 edited this page Mar 10, 2018
·
5 revisions
<?php
namespace App\Tasks\Test;
use App\Tasks\System\Socket;
use swoole_server;
use Swoole\Client;
use swoole_client;
class TestTask extends Socket
{
protected function events()
{
return [
'receive' => [$this, 'receive'],
];
}
protected function beforeServerStart(swoole_server $server)
{
parent::beforeServerStart($server); // TODO: Change the autogenerated stub
$process = new swoole_process(function (swoole_process $worker) use ($server) {
if (!file_exists(ROOT_PATH . '/tick.lock')) {
file_put_contents(ROOT_PATH . '/tick.lock', 1);
}
swoole_timer_tick(1000, function () use ($worker) {
if (file_get_contents(ROOT_PATH . '/tick.lock')) {
echo 'tick:' . time() . ':' . $worker->pid . PHP_EOL;
}
});
});
$server->addProcess($process);
}
public function receive(swoole_server $server, $fd, $reactor_id, $data)
{
echo $data . PHP_EOL;
$server->send($fd, 'SERVER RECEIVED:' . $data);
}
public function tcpAction()
{
$client = new Client(SWOOLE_TCP, SWOOLE_SOCK_ASYNC);
$client->on('receive', function (swoole_client $client, $data) {
echo $data . PHP_EOL;
$client->close();
});
$client->on('connect', function (swoole_client $client) {
echo 'connect' . PHP_EOL;
$client->send('hello world');
});
$client->on('error', function (swoole_client $client) {
echo 'error' . PHP_EOL;
});
$client->on('close', function (swoole_client $client) {
echo 'close' . PHP_EOL;
});
$client->connect('127.0.0.1', $this->port);
}
}
# 启动server
php run test:test
# 测试
php run test:test@tcp
- 新建socket.service
[Unit]
Description=Socket Server
After=network.target
After=syslog.target
[Service]
Type=forking
PIDFile=/opt/www/phalcon/socket.pid
ExecStart=/usr/local/bin/php /opt/www/phalcon/run server
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID
Restart=always
[Install]
WantedBy=multi-user.target graphical.target
- 移动socket.service 到 /etc/systemd/system
注意,这里不能建立软连接,如果非要建立软连接,请确保每个项目内socket.service不要重名
- 开机启动
systemctl enable socket.service
就会在/etc/systemd/system/multi-user.target.wants/目录下新建一个/usr/lib/systemd/system/socket.service 文件的链接。