swoole的安装与使用
Eave
2017.09.06 14:06
从https://github.com/swoole/swoole-src下载swoole扩展包
$ wget -O swoole-master.zip https://github.com/swoole/swoole-src/archive/master.zip
$ unzip swoole-master.zip
$ cd swoole-src-master
$ /usr/local/php/bin/phpize
$ ./configure --with-php-config=/usr/local/php/bin/php-config --enable-coroutine
$ make && make install
代码示例
TCP server
// Create a server instance
$serv = new swoole_server('127.0.0.1', 9501);
$config = array(
'backlog' => 128,
'worker_num' => 8, // 工作进程数量
'daemonize' => true, // 是否作为守护进程
'log_file' => '/var/log/tcpserver/swoole.log',
'open_eof_check' => true,
'open_eof_split' => true,
'package_eof' => "\n",
'heartbeat_check_interval' => 300,
'heartbeat_idle_time' => 300
);
$serv->set($config);
// Attach handler for connect event. Once the client has connected to the server, the registered handler will be
// executed.
$serv->on('connect', function($serv, $fd)
{
echo "Client:Connect.\n";
});
// Attach handler for receive event. Every piece of data will be received by server and the registered handler will be
// executed. All custom protocol implementation should be located there.
$serv->on('receive', function($serv, $fd, $from_id, $data)
{
$serv->send($fd, $data);
});
$serv->on('close', function($serv, $fd)
{
echo "Client: Close.\n";
});
// Start our server, listen on the port and be ready to accept connections.
$serv->start();
websocket
$serv = new swoole_websocket_server("0.0.0.0", 9502);
$serv->on('open', function($serv, $frame)
{
print_r($request->fd);
print_r($request->get);
print_r($request->server);
$serv->push($frame->fd, "hello, welcome\n");
});
$serv->on('message', function($serv, $frame)
{
echo "Message: {$frame->data}\n";
$serv->push($frame->fd, "server: {$frame->data}");
});
$serv->on('close', function($serv, $fd)
{
echo "client-{$fd} is closed\n";
});
$serv->start();