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

Commit 02c9f10

Browse files
committed
add HandShakeHandler
1 parent 3447ac6 commit 02c9f10

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/Websocket/HandShakeHandler.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace SwooleTW\Http\Websocket;
4+
5+
/**
6+
* Class HandShakeHandler
7+
*/
8+
class HandShakeHandler
9+
{
10+
/**
11+
* @see https://www.swoole.co.uk/docs/modules/swoole-websocket-server
12+
*
13+
* @param \Swoole\Http\Request $request
14+
* @param \Swoole\Http\Response $response
15+
*
16+
* @return bool
17+
*/
18+
public function handle($request, $response)
19+
{
20+
$socketkey = $request->header['sec-websocket-key'];
21+
22+
if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $socketkey) || 16 !== strlen(base64_decode($socketkey))) {
23+
$response->end();
24+
25+
return false;
26+
}
27+
28+
$headers = [
29+
'Upgrade' => 'websocket',
30+
'Connection' => 'Upgrade',
31+
'Sec-WebSocket-Accept' => base64_encode(sha1($socketkey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)),
32+
'Sec-WebSocket-Version' => '13',
33+
];
34+
35+
if (isset($request->header['sec-websocket-protocol'])) {
36+
$headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol'];
37+
}
38+
39+
foreach ($headers as $header => $val) {
40+
$response->header($header, $val);
41+
}
42+
43+
$response->status(101);
44+
$response->end();
45+
46+
return true;
47+
}
48+
}

0 commit comments

Comments
 (0)