Skip to content
This repository was archived by the owner on Mar 24, 2025. It is now read-only.

Commit d0700ce

Browse files
authored
Merge pull request #65 from swooletw/develop
Develop
2 parents 1307c4e + 2b8f3e0 commit d0700ce

File tree

11 files changed

+108
-20
lines changed

11 files changed

+108
-20
lines changed

composer.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
"codedungeon/phpunit-result-printer": "^0.14.0"
2929
},
3030
"autoload": {
31+
"files": [
32+
"src/Server/helpers.php"
33+
],
3134
"psr-4": {
3235
"SwooleTW\\Http\\": "src"
3336
}

src/Commands/HttpServerCommand.php

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ protected function start()
8989
$this->info("Swoole http server started: <http://{$host}:{$port}>");
9090
if ($this->isDaemon()) {
9191
$this->info('> (You can run this command to ensure the ' .
92-
'swoole_http_server process is running: ps aux|grep "swoole")');
92+
'swoole_http_server process is running: ps aux|grep "swoole")');
9393
}
9494

9595
$this->laravel->make('swoole.http')->run();
@@ -161,7 +161,6 @@ protected function reload()
161161
$this->info('> success');
162162
}
163163

164-
165164
/**
166165
* Display PHP and Swoole misc info.
167166
*/
@@ -172,27 +171,37 @@ protected function infos()
172171

173172
/**
174173
* Display PHP and Swoole miscs infos.
174+
*
175+
* @param bool $more
175176
*/
176177
protected function showInfos()
177178
{
178179
$pid = $this->getPid();
179180
$isRunning = $this->isRunning($pid);
180181
$host = $this->configs['server']['host'];
181182
$port = $this->configs['server']['port'];
183+
$reactorNum = $this->configs['server']['options']['reactor_num'];
184+
$workerNum = $this->configs['server']['options']['worker_num'];
185+
$taskWorkerNum = $this->configs['server']['options']['task_worker_num'];
182186
$isWebsocket = $this->configs['websocket']['enabled'];
183187
$logFile = $this->configs['server']['options']['log_file'];
184188

185-
$this->table(['Name', 'Value'], [
189+
$table = [
186190
['PHP Version', 'Version' => phpversion()],
187191
['Swoole Version', 'Version' => swoole_version()],
188192
['Laravel Version', $this->getApplication()->getVersion()],
189-
['Server Status', $isRunning ? 'Online' : 'Offline'],
190193
['Listen IP', $host],
191194
['Listen Port', $port],
195+
['Server Status', $isRunning ? 'Online' : 'Offline'],
196+
['Reactor Num', $reactorNum],
197+
['Worker Num', $workerNum],
198+
['Task Worker Num', $isWebsocket ? $taskWorkerNum : 0],
192199
['Websocket Mode', $isWebsocket ? 'On' : 'Off'],
193200
['PID', $isRunning ? $pid : 'None'],
194201
['Log Path', $logFile],
195-
]);
202+
];
203+
204+
$this->table(['Name', 'Value'], $table);
196205
}
197206

198207
/**

src/HttpServiceProvider.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,10 @@ public function boot()
5252
__DIR__ . '/../config/swoole_websocket.php' => base_path('config/swoole_websocket.php'),
5353
__DIR__ . '/../routes/websocket.php' => base_path('routes/websocket.php')
5454
], 'laravel-swoole');
55-
$this->bootRoutes();
55+
56+
if ($this->app['config']->get('swoole_http.websocket.enabled')) {
57+
$this->bootRoutes();
58+
}
5659
}
5760

5861
/**

src/Server/Manager.php

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,11 @@ protected function configureSwooleServer()
154154
{
155155
$config = $this->container['config']->get('swoole_http.server.options');
156156

157+
// only enable task worker in websocket mode
158+
if (! $this->isWebsocket) {
159+
unset($config['task_worker_num']);
160+
}
161+
157162
$this->server->set($config);
158163
}
159164

@@ -246,7 +251,7 @@ public function onRequest($swooleRequest, $swooleResponse)
246251
return;
247252
}
248253

249-
// set currnt request to sandbox
254+
// set current request to sandbox
250255
$this->sandbox->setRequest($illuminateRequest);
251256

252257
// enable sandbox
@@ -257,9 +262,6 @@ public function onRequest($swooleRequest, $swooleResponse)
257262
$illuminateResponse = $application->run($illuminateRequest);
258263
$response = Response::make($illuminateResponse, $swooleResponse);
259264
$response->send();
260-
261-
// disable and recycle sandbox resource
262-
$this->sandbox->disable();
263265
} catch (Exception $e) {
264266
try {
265267
$exceptionResponse = $this->app[ExceptionHandler::class]->render($illuminateRequest, $e);
@@ -268,6 +270,9 @@ public function onRequest($swooleRequest, $swooleResponse)
268270
} catch (Exception $e) {
269271
$this->logServerError($e);
270272
}
273+
} finally {
274+
// disable and recycle sandbox resource
275+
$this->sandbox->disable();
271276
}
272277
}
273278

@@ -276,6 +281,7 @@ public function onRequest($swooleRequest, $swooleResponse)
276281
*
277282
* @param \Illuminate\Http\Request $illuminateRequest
278283
* @param \Swoole\Http\Response $swooleResponse
284+
* @return boolean
279285
*/
280286
protected function handleStaticRequest($illuminateRequest, $swooleResponse)
281287
{
@@ -320,7 +326,7 @@ protected function resetOnRequest()
320326
/**
321327
* Set onTask listener.
322328
*/
323-
public function onTask(HttpServer $server, $taskId, $fromId, $data)
329+
public function onTask(HttpServer $server, $taskId, $srcWorkerId, $data)
324330
{
325331
$this->container['events']->fire('swoole.task', func_get_args());
326332

@@ -440,7 +446,11 @@ protected function createPidFile()
440446
*/
441447
protected function removePidFile()
442448
{
443-
unlink($this->getPidFile());
449+
$pidFile = $this->getPidFile();
450+
451+
if (file_exists($pidFile)) {
452+
unlink($pidFile);
453+
}
444454
}
445455

446456
/**

src/Server/Sandbox.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,8 @@ protected function resetSession($application)
213213
protected function resetCookie($application)
214214
{
215215
if (isset($application['cookie'])) {
216-
foreach ($application->make('cookie')->getQueuedCookies() as $key => $value) {
216+
$cookies = $application->make('cookie');
217+
foreach ($cookies->getQueuedCookies() as $key => $value) {
217218
$cookies->unqueue($key);
218219
}
219220
}

src/Server/helpers.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
/**
4+
* This is only for `function not exists` in config/swoole_http.php.
5+
*/
6+
if (! function_exists('swoole_cpu_num')) {
7+
function swoole_cpu_num()
8+
{
9+
return;
10+
}
11+
}

src/Table/SwooleTable.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class SwooleTable
1818
*
1919
* @param string $name
2020
* @param \Swoole\Table $table
21+
* @return \SwooleTW\Http\Table\SwooleTable
2122
*/
2223
public function add(string $name, Table $table)
2324
{

src/Websocket/Authenticatable.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ public function loginUsingId($userId)
2525
return $this->join(static::USER_PREFIX . $userId);
2626
}
2727

28+
/**
29+
* Logout with current sender's fd.
30+
*/
31+
public function logout()
32+
{
33+
if (is_null($userId = $this->getUserId())) {
34+
return;
35+
}
36+
37+
return $this->leave(static::USER_PREFIX . $userId);
38+
}
39+
2840
/**
2941
* Set multiple recepients' fds by users.
3042
*/
@@ -75,6 +87,14 @@ public function getUserId()
7587
return $this->userId;
7688
}
7789

90+
/**
91+
* Check if a user is online by given userId.
92+
*/
93+
public function isUserIdOnline($userId)
94+
{
95+
return ! empty($this->room->getClients(static::USER_PREFIX . $userId));
96+
}
97+
7898
/**
7999
* Check if user object implements AuthenticatableContract.
80100
*/

src/Websocket/CanWebsocket.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,11 @@ public function onOpen(Server $server, $swooleRequest)
7474
$this->websocket->setContainer($application);
7575
$this->websocket->call('connect', $illuminateRequest);
7676
}
77-
// disable and recycle sandbox resource
78-
$this->sandbox->disable();
7977
} catch (Exception $e) {
8078
$this->logServerError($e);
79+
} finally {
80+
// disable and recycle sandbox resource
81+
$this->sandbox->disable();
8182
}
8283
}
8384

@@ -112,10 +113,11 @@ public function onMessage(Server $server, Frame $frame)
112113
} else {
113114
$this->websocketHandler->onMessage($frame);
114115
}
115-
// disable and recycle sandbox resource
116-
$this->sandbox->disable();
117116
} catch (Exception $e) {
118117
$this->logServerError($e);
118+
} finally {
119+
// disable and recycle sandbox resource
120+
$this->sandbox->disable();
119121
}
120122
}
121123

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

135137
try {
136-
// leave all rooms
137-
$this->websocket->reset(true)->setSender($fd)->leave();
138+
$this->websocket->reset(true)->setSender($fd);
138139
// trigger 'disconnect' websocket event
139140
if ($this->websocket->eventExists('disconnect')) {
140141
$this->websocket->call('disconnect');
141142
} else {
142143
$this->websocketHandler->onClose($fd, $reactorId);
143144
}
145+
// leave all rooms
146+
$this->websocket->leave();
144147
} catch (Exception $e) {
145148
$this->logServerError($e);
146149
}

src/Websocket/Websocket.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ protected function getFds()
296296

297297
foreach ($rooms as $room) {
298298
$clients = $this->room->getClients($room);
299-
// rollback fd with wrong type back to fds array
299+
// fallback fd with wrong type back to fds array
300300
if (empty($clients) && is_numeric($room)) {
301301
$fds[] = $room;
302302
} else {

tests/Websocket/WebsocketTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,33 @@ public function testGetUserId()
205205
$this->assertEquals($sender, $websocket->getUserId());
206206
}
207207

208+
public function testLogout()
209+
{
210+
$room = m::mock(RoomContract::class);
211+
$room->shouldReceive('getRooms')
212+
->with($sender = 1)
213+
->once()
214+
->andReturn(['uid_1']);
215+
$room->shouldReceive('delete')
216+
->with($sender, $name = ['uid_1'])
217+
->once();
218+
219+
$websocket = $this->getWebsocket($room)->setSender($sender);
220+
$websocket->logout();
221+
}
222+
223+
public function testIsUserIdOnline()
224+
{
225+
$room = m::mock(RoomContract::class);
226+
$room->shouldReceive('getClients')
227+
->with('uid_1')
228+
->once()
229+
->andReturn([1]);
230+
231+
$websocket = $this->getWebsocket($room);
232+
$this->assertTrue($websocket->isUserIdOnline(1));
233+
}
234+
208235
public function testReset()
209236
{
210237
$websocket = $this->getWebsocket();

0 commit comments

Comments
 (0)