aboutsummaryrefslogtreecommitdiffhomepage
path: root/assets/php/vendor/ratchet/rfc6455/tests/ab/startServer.php
blob: b256ec2908bec57a9fa606907fb747e3b69a6c7b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\RFC6455\Messaging\FrameInterface;
use Ratchet\RFC6455\Messaging\Frame;

require_once __DIR__ . "/../bootstrap.php";

$loop   = \React\EventLoop\Factory::create();

$socket = new \React\Socket\Server($loop);
$server = new \React\Http\Server($socket);

$closeFrameChecker = new \Ratchet\RFC6455\Messaging\CloseFrameChecker;
$negotiator = new \Ratchet\RFC6455\Handshake\ServerNegotiator(new \Ratchet\RFC6455\Handshake\RequestVerifier);

$uException = new \UnderflowException;

$server->on('request', function (\React\Http\Request $request, \React\Http\Response $response) use ($negotiator, $closeFrameChecker, $uException) {
    $psrRequest = new \GuzzleHttp\Psr7\Request($request->getMethod(), $request->getPath(), $request->getHeaders());

    $negotiatorResponse = $negotiator->handshake($psrRequest);

    $response->writeHead(
        $negotiatorResponse->getStatusCode(),
        array_merge(
            $negotiatorResponse->getHeaders(),
            ["Content-Length" => "0"]
        )
    );

    if ($negotiatorResponse->getStatusCode() !== 101) {
        $response->end();
        return;
    }

    $parser = new \Ratchet\RFC6455\Messaging\MessageBuffer($closeFrameChecker, function(MessageInterface $message) use ($response) {
        $response->write($message->getContents());
    }, function(FrameInterface $frame) use ($response, &$parser) {
        switch ($frame->getOpCode()) {
            case Frame::OP_CLOSE:
                $response->end($frame->getContents());
                break;
            case Frame::OP_PING:
                $response->write($parser->newFrame($frame->getPayload(), true, Frame::OP_PONG)->getContents());
                break;
        }
    }, true, function() use ($uException) {
        return $uException;
    });

    $request->on('data', [$parser, 'onData']);
});

$socket->listen(9001, '0.0.0.0');
$loop->run();