Completed
Push — master ( 24a50e...68cda6 )
by Arthur
02:20
created

ServerHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace WSSCTEST;
4
5
use WSSC\Contracts\ConnectionContract;
6
use WSSC\Contracts\WebSocket;
7
use WSSC\Exceptions\WebSocketException;
8
use Monolog\Logger;
9
use Monolog\Handler\StreamHandler;
10
11
class ServerHandler extends WebSocket
12
{
13
14
    /*
15
     *  if You need to parse URI context like /messanger/chat/JKN324jn4213
16
     *  You can do so by placing URI parts into an array - $pathParams, when Socket will receive a connection 
17
     *  this variable will be appropriately set to key => value pairs, ex.: ':context' => 'chat'
18
     *  Otherwise leave $pathParams as an empty array
19
     */
20
21
    public $pathParams = [':entity', ':context', ':token'];
22
    private $clients = [];
23
24
    private $log;
25
26
    /**
27
     * ServerHandler constructor.
28
     *
29
     * @throws \Exception
30
     */
31
    public function __construct()
32
    {
33
        // create a log channel
34
        $this->log = new Logger('ServerSocket');
35
        $this->log->pushHandler(new StreamHandler('./tests/tests.log'));
36
    }
37
38
    public function onOpen(ConnectionContract $conn)
39
    {
40
        $this->clients[] = $conn;
41
        $this->log->debug(print_r($this->clients, 1));
42
        echo 'Connection opend, total clients: ' . count($this->clients) . PHP_EOL;
43
    }
44
45
    public function onMessage(ConnectionContract $recv, $msg)
46
    {
47
        echo 'Received message:  ' . $msg . PHP_EOL;
48
        $recv->send($msg);
49
    }
50
51
    public function onClose(ConnectionContract $conn)
52
    {
53
        unset($this->clients[array_search($conn, $this->clients)]);
54
        $conn->close();
55
    }
56
57
    /**
58
     * @param ConnectionContract $conn
59
     * @param WebSocketException $ex
60
     */
61
    public function onError(ConnectionContract $conn, WebSocketException $ex)
62
    {
63
        echo 'Error occured: ' . $ex->printStack();
64
    }
65
66
    /**
67
     * You may want to implement these methods to bring ping/pong events
68
     * @param ConnectionContract $conn
69
     * @param string $msg
70
     */
71
    public function onPing(ConnectionContract $conn, $msg)
72
    {
73
        // TODO: Implement onPing() method.
74
    }
75
76
    /**
77
     * @param ConnectionContract $conn
78
     * @param $msg
79
     * @return mixed
80
     */
81
    public function onPong(ConnectionContract $conn, $msg)
82
    {
83
        // TODO: Implement onPong() method.
84
    }
85
}
86