Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #65 from swooletw/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
albertcht authored May 26, 2018
2 parents 1307c4e + 2b8f3e0 commit d0700ce
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 20 deletions.
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
"codedungeon/phpunit-result-printer": "^0.14.0"
},
"autoload": {
"files": [
"src/Server/helpers.php"
],
"psr-4": {
"SwooleTW\\Http\\": "src"
}
Expand Down
19 changes: 14 additions & 5 deletions src/Commands/HttpServerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ protected function start()
$this->info("Swoole http server started: <http://{$host}:{$port}>");
if ($this->isDaemon()) {
$this->info('> (You can run this command to ensure the ' .
'swoole_http_server process is running: ps aux|grep "swoole")');
'swoole_http_server process is running: ps aux|grep "swoole")');
}

$this->laravel->make('swoole.http')->run();
Expand Down Expand Up @@ -161,7 +161,6 @@ protected function reload()
$this->info('> success');
}


/**
* Display PHP and Swoole misc info.
*/
Expand All @@ -172,27 +171,37 @@ protected function infos()

/**
* Display PHP and Swoole miscs infos.
*
* @param bool $more
*/
protected function showInfos()
{
$pid = $this->getPid();
$isRunning = $this->isRunning($pid);
$host = $this->configs['server']['host'];
$port = $this->configs['server']['port'];
$reactorNum = $this->configs['server']['options']['reactor_num'];
$workerNum = $this->configs['server']['options']['worker_num'];
$taskWorkerNum = $this->configs['server']['options']['task_worker_num'];
$isWebsocket = $this->configs['websocket']['enabled'];
$logFile = $this->configs['server']['options']['log_file'];

$this->table(['Name', 'Value'], [
$table = [
['PHP Version', 'Version' => phpversion()],
['Swoole Version', 'Version' => swoole_version()],
['Laravel Version', $this->getApplication()->getVersion()],
['Server Status', $isRunning ? 'Online' : 'Offline'],
['Listen IP', $host],
['Listen Port', $port],
['Server Status', $isRunning ? 'Online' : 'Offline'],
['Reactor Num', $reactorNum],
['Worker Num', $workerNum],
['Task Worker Num', $isWebsocket ? $taskWorkerNum : 0],
['Websocket Mode', $isWebsocket ? 'On' : 'Off'],
['PID', $isRunning ? $pid : 'None'],
['Log Path', $logFile],
]);
];

$this->table(['Name', 'Value'], $table);
}

/**
Expand Down
5 changes: 4 additions & 1 deletion src/HttpServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ public function boot()
__DIR__ . '/../config/swoole_websocket.php' => base_path('config/swoole_websocket.php'),
__DIR__ . '/../routes/websocket.php' => base_path('routes/websocket.php')
], 'laravel-swoole');
$this->bootRoutes();

if ($this->app['config']->get('swoole_http.websocket.enabled')) {
$this->bootRoutes();
}
}

/**
Expand Down
22 changes: 16 additions & 6 deletions src/Server/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ protected function configureSwooleServer()
{
$config = $this->container['config']->get('swoole_http.server.options');

// only enable task worker in websocket mode
if (! $this->isWebsocket) {
unset($config['task_worker_num']);
}

$this->server->set($config);
}

Expand Down Expand Up @@ -246,7 +251,7 @@ public function onRequest($swooleRequest, $swooleResponse)
return;
}

// set currnt request to sandbox
// set current request to sandbox
$this->sandbox->setRequest($illuminateRequest);

// enable sandbox
Expand All @@ -257,9 +262,6 @@ public function onRequest($swooleRequest, $swooleResponse)
$illuminateResponse = $application->run($illuminateRequest);
$response = Response::make($illuminateResponse, $swooleResponse);
$response->send();

// disable and recycle sandbox resource
$this->sandbox->disable();
} catch (Exception $e) {
try {
$exceptionResponse = $this->app[ExceptionHandler::class]->render($illuminateRequest, $e);
Expand All @@ -268,6 +270,9 @@ public function onRequest($swooleRequest, $swooleResponse)
} catch (Exception $e) {
$this->logServerError($e);
}
} finally {
// disable and recycle sandbox resource
$this->sandbox->disable();
}
}

Expand All @@ -276,6 +281,7 @@ public function onRequest($swooleRequest, $swooleResponse)
*
* @param \Illuminate\Http\Request $illuminateRequest
* @param \Swoole\Http\Response $swooleResponse
* @return boolean
*/
protected function handleStaticRequest($illuminateRequest, $swooleResponse)
{
Expand Down Expand Up @@ -320,7 +326,7 @@ protected function resetOnRequest()
/**
* Set onTask listener.
*/
public function onTask(HttpServer $server, $taskId, $fromId, $data)
public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data)
{
$this->container['events']->fire('swoole.task', func_get_args());

Expand Down Expand Up @@ -440,7 +446,11 @@ protected function createPidFile()
*/
protected function removePidFile()
{
unlink($this->getPidFile());
$pidFile = $this->getPidFile();

if (file_exists($pidFile)) {
unlink($pidFile);
}
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Server/Sandbox.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ protected function resetSession($application)
protected function resetCookie($application)
{
if (isset($application['cookie'])) {
foreach ($application->make('cookie')->getQueuedCookies() as $key => $value) {
$cookies = $application->make('cookie');
foreach ($cookies->getQueuedCookies() as $key => $value) {
$cookies->unqueue($key);
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/Server/helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

/**
* This is only for `function not exists` in config/swoole_http.php.
*/
if (! function_exists('swoole_cpu_num')) {
function swoole_cpu_num()
{
return;
}
}
1 change: 1 addition & 0 deletions src/Table/SwooleTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class SwooleTable
*
* @param string $name
* @param \Swoole\Table $table
* @return \SwooleTW\Http\Table\SwooleTable
*/
public function add(string $name, Table $table)
{
Expand Down
20 changes: 20 additions & 0 deletions src/Websocket/Authenticatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ public function loginUsingId($userId)
return $this->join(static::USER_PREFIX . $userId);
}

/**
* Logout with current sender's fd.
*/
public function logout()
{
if (is_null($userId = $this->getUserId())) {
return;
}

return $this->leave(static::USER_PREFIX . $userId);
}

/**
* Set multiple recepients' fds by users.
*/
Expand Down Expand Up @@ -75,6 +87,14 @@ public function getUserId()
return $this->userId;
}

/**
* Check if a user is online by given userId.
*/
public function isUserIdOnline($userId)
{
return ! empty($this->room->getClients(static::USER_PREFIX . $userId));
}

/**
* Check if user object implements AuthenticatableContract.
*/
Expand Down
15 changes: 9 additions & 6 deletions src/Websocket/CanWebsocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ public function onOpen(Server $server, $swooleRequest)
$this->websocket->setContainer($application);
$this->websocket->call('connect', $illuminateRequest);
}
// disable and recycle sandbox resource
$this->sandbox->disable();
} catch (Exception $e) {
$this->logServerError($e);
} finally {
// disable and recycle sandbox resource
$this->sandbox->disable();
}
}

Expand Down Expand Up @@ -112,10 +113,11 @@ public function onMessage(Server $server, Frame $frame)
} else {
$this->websocketHandler->onMessage($frame);
}
// disable and recycle sandbox resource
$this->sandbox->disable();
} catch (Exception $e) {
$this->logServerError($e);
} finally {
// disable and recycle sandbox resource
$this->sandbox->disable();
}
}

Expand All @@ -133,14 +135,15 @@ public function onClose(Server $server, $fd, $reactorId)
}

try {
// leave all rooms
$this->websocket->reset(true)->setSender($fd)->leave();
$this->websocket->reset(true)->setSender($fd);
// trigger 'disconnect' websocket event
if ($this->websocket->eventExists('disconnect')) {
$this->websocket->call('disconnect');
} else {
$this->websocketHandler->onClose($fd, $reactorId);
}
// leave all rooms
$this->websocket->leave();
} catch (Exception $e) {
$this->logServerError($e);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Websocket/Websocket.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ protected function getFds()

foreach ($rooms as $room) {
$clients = $this->room->getClients($room);
// rollback fd with wrong type back to fds array
// fallback fd with wrong type back to fds array
if (empty($clients) && is_numeric($room)) {
$fds[] = $room;
} else {
Expand Down
27 changes: 27 additions & 0 deletions tests/Websocket/WebsocketTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,33 @@ public function testGetUserId()
$this->assertEquals($sender, $websocket->getUserId());
}

public function testLogout()
{
$room = m::mock(RoomContract::class);
$room->shouldReceive('getRooms')
->with($sender = 1)
->once()
->andReturn(['uid_1']);
$room->shouldReceive('delete')
->with($sender, $name = ['uid_1'])
->once();

$websocket = $this->getWebsocket($room)->setSender($sender);
$websocket->logout();
}

public function testIsUserIdOnline()
{
$room = m::mock(RoomContract::class);
$room->shouldReceive('getClients')
->with('uid_1')
->once()
->andReturn([1]);

$websocket = $this->getWebsocket($room);
$this->assertTrue($websocket->isUserIdOnline(1));
}

public function testReset()
{
$websocket = $this->getWebsocket();
Expand Down

0 comments on commit d0700ce

Please sign in to comment.