Skip to content

Commit c9ef8e2

Browse files
authored
Fixed bug that WsContext does not work in onOpen. (#4614)
1 parent 4bcaa5d commit c9ef8e2

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

src/Server.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,13 +150,13 @@ public function onHandShake($request, $response): void
150150

151151
// TODO: Support SWOW
152152
$response instanceof SwooleResponse && $this->getSender()->setResponse($fd, $response);
153-
$this->deferOnOpen($request, $class, $response);
153+
$this->deferOnOpen($request, $class, $response, $fd);
154154

155155
$upgrade->on(WebSocket::ON_MESSAGE, $this->getOnMessageCallback());
156156
$upgrade->on(WebSocket::ON_CLOSE, $this->getOnCloseCallback());
157157
$upgrade->start();
158158
} else {
159-
$this->deferOnOpen($request, $class, $server);
159+
$this->deferOnOpen($request, $class, $server, $fd);
160160
}
161161
} catch (Throwable $throwable) {
162162
// Delegate the exception to exception handler.
@@ -234,10 +234,11 @@ protected function getFd($response): int
234234
/**
235235
* @param mixed $request
236236
*/
237-
protected function deferOnOpen($request, string $class, SwooleResponse|WebSocketServer $server)
237+
protected function deferOnOpen($request, string $class, SwooleResponse|WebSocketServer $server, int $fd)
238238
{
239239
$instance = $this->container->get($class);
240-
wait(static function () use ($request, $instance, $server) {
240+
wait(static function () use ($request, $instance, $server, $fd) {
241+
Context::set(WsContext::FD, $fd);
241242
if ($instance instanceof OnOpenInterface) {
242243
$instance->onOpen($server, $request);
243244
}

tests/ServerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public function testDeferOnOpenInCoroutineStyleServer()
5454
);
5555

5656
$server = new ClassInvoker($server);
57-
$server->deferOnOpen(new SwooleRequest(), WebSocketStub::class, new SwooleResponse());
57+
$server->deferOnOpen(new SwooleRequest(), WebSocketStub::class, new SwooleResponse(), 1);
5858
$this->assertNotEquals(Coroutine::id(), WebSocketStub::$coroutineId);
5959
$this->assertFalse(\Swoole\Coroutine::exists(WebSocketStub::$coroutineId));
6060
}

0 commit comments

Comments
 (0)