Skip to content

Commit fcb0f5e

Browse files
committed
fix(http): properly close stream when connection is set to 'close'
1 parent 2ce00ed commit fcb0f5e

2 files changed

Lines changed: 12 additions & 12 deletions

File tree

src/Net/Http/Server/Connection.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -245,15 +245,13 @@ private function onRequest(array $reqInfo): void
245245
// 半关闭检测
246246
$connHeader = $reqInfo['server']['HTTP_CONNECTION'] ?? '';
247247
$upgradeHeader = $reqInfo['server']['HTTP_UPGRADE'] ?? '';
248-
$keepAlive = strtolower($connHeader) === 'keep-alive';
249-
$isWebSocketUpgrade = strtolower($upgradeHeader) === 'websocket' &&
250-
str_contains(strtolower($connHeader), 'upgrade');
248+
$keepAlive = strtolower($connHeader) !== 'close';
249+
$isWebSocketUpgrade = strtolower($upgradeHeader) === 'websocket' && str_contains(strtolower($connHeader), 'upgrade');
251250

252251
if ($keepAlive || $isWebSocketUpgrade) {
253252
$response->withHeader('Connection', $keepAlive ? 'keep-alive' : 'Upgrade');
254253
} else {
255254
$response->withHeader('Connection', 'close');
256-
$this->stream->shutdownRead();
257255
}
258256

259257
try {
@@ -263,6 +261,8 @@ private function onRequest(array $reqInfo): void
263261
} catch (Throwable $exception) {
264262
$req->respond($exception->getMessage(), [], 500);
265263
$this->reset();
264+
} finally {
265+
($keepAlive || $isWebSocketUpgrade) || $this->disconnect();
266266
}
267267
}
268268

src/Net/WebSocket/Server/Server.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,16 @@ private function handleWebSocketRequest(Request $request): ?Connection
8080
return null;
8181
}
8282

83+
if (!$this->performHandshake($request)) {
84+
$request->respond('Bad Request', [], 400);
85+
return null;
86+
}
87+
88+
$connection = new Connection($request->conn->stream, $request);
89+
8390
if (isset($this->onRequest)) {
8491
try {
85-
$result = ($this->onRequest)($request);
92+
$result = ($this->onRequest)($request, $connection);
8693
if ($result === false) {
8794
$request->respond('Forbidden', [], 403);
8895
return null;
@@ -93,13 +100,6 @@ private function handleWebSocketRequest(Request $request): ?Connection
93100
}
94101
}
95102

96-
if (!$this->performHandshake($request)) {
97-
$request->respond('Bad Request', [], 400);
98-
return null;
99-
}
100-
101-
$connection = new Connection($request->conn->stream, $request);
102-
103103
if (isset($this->onConnect)) {
104104
$handler = $this->onConnect;
105105
go(fn () => $handler($connection));

0 commit comments

Comments
 (0)