swoole常用服务的创建
1,tcp
//创建Server对象,监听 127.0.0.1:9501 端口 $server = new Swoole\Server('127.0.0.1', 9501); //监听连接进入事件 $server->on('Connect', function ($server, $fd) { echo "Client: Connect.\n"; }); //监听数据接收事件 $server->on('Receive', function ($server, $fd, $reactor_id, $data) { $server->send($fd, "Server: {$data}"); }); //监听连接关闭事件 $server->on('Close', function ($server, $fd) { echo "Client: Close.\n"; }); //启动服务器 $server->start();
2,http
$http = new Swoole\Http\Server('0.0.0.0', 9501); $http->on('Request', function ($request, $response) { $response->header('Content-Type', 'text/html; charset=utf-8'); $response->end('<h1>Hello Swoole. #' . rand(1000, 9999) . '</h1>'); }); $http->start();