forked from kallaspriit/PHP-HTML5-WebSocket-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketServer.php
executable file
·856 lines (721 loc) · 18.4 KB
/
SocketServer.php
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
<?php
/**
* Simple WebSocket server implementation.
*
* Copyright (C) <2012> by <Priit Kallas>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Based on snippets from http://code.google.com/p/phpwebsocket/
* and http://bohuco.net/blog/2010/07/html5-websockets-example/.
*
* @author Priit Kallas <kallaspriit@gmail.com>
* @package WebSocket
*/
/**
* Socket server listener interface.
*
* Implement this to communicate with the socket server.
*
* @author Priit Kallas <kallaspriit@gmail.com>
* @package WebSocket
*/
interface SocketListener {
/**
* Called when a client sends a message to the server.
*
* @param SocketServer $server The server instance
* @param SocketClient $client Client that sent the message
* @param string $message Sent message
*/
public function onMessageRecieved(
SocketServer $server,
SocketClient $sender,
$message
);
/**
* Called when a new client connects to the server.
*
* @param SocketServer $server The server instance
* @param SocketClient $client Client that connected
*/
public function onClientConnected(
SocketServer $server,
SocketClient $client
);
/**
* Called when a client disconnects from the server.
*
* @param SocketServer $server The server instance
* @param SocketClient $client Client that disconnected
*/
public function onClientDisconnected(
SocketServer $server,
SocketClient $client
);
/**
* Called when the server generates a log message.
*
* @param SocketServer $server The server
* @param string $message Log message
*/
public function onLogMessage(
SocketServer $server,
$message
);
}
/**
* Simple WebSocket server.
*
* @author Priit Kallas <kallaspriit@gmail.com>
* @package WebSocket
*/
Class SocketServer {
/**
* Host to bind to.
*
* @var string
*/
protected $host;
/**
* Port number where to bind to.
*
* @var integer
*/
protected $port;
/**
* Array of connected clients.
*
* @var SocketClient[]
*/
protected $clients = array();
/**
* The master socket acting as server.
*
* @var resource
*/
protected $socket;
/**
* Array of all connected sockets, includes the master.
*
* @var resource[]
*/
protected $sockets = array();
/**
* Array of socket listeners.
*
* @var SocketListener[]
*/
protected $listeners = array();
const FIN = 128;
const MASK = 128;
const OPCODE_CONTINUATION = 0;
const OPCODE_TEXT = 1;
const PAYLOAD_LENGTH_16 = 126;
const PAYLOAD_LENGTH_63 = 127;
/**
* Constructor, sets host and port to bind to.
*
* @param string $host Socket host to bind to, defaults to localhost
* @param integer $port Port to bind to, defaults to 8080
*/
public function __construct(
$host = '127.0.0.1',
$port = 8080
) {
$this->host = $host;
$this->port = $port;
}
/**
* Adds a new socket listener.
*
* @param SocketListener $listener Listener to add
*/
public function addListener(SocketListener $listener) {
$this->listeners[] = $listener;
}
/**
* Removes an existing socket listener.
*
* @param SocketListener $listener Listener to remove
* @return boolean Was the listener removed, false if not found
*/
public function removeListener(SocketListener $listener) {
foreach ($this->listeners as $key => $socketListener) {
if ($socketListener == $listener) {
unset($this->listeners[$key]);
return true;
}
}
return false;
}
/**
* Returns all added socket listeners.
*
* @return SocketListener[]
*/
public function getListeners() {
return $this->listeners;
}
/**
* Sets the host to use.
*
* Only has effect before starting the server.
*
* @param string $host Host to bind to
*/
public function setHost($host) {
$this->host = $host;
}
/**
* Sets the host port to use.
*
* Only has effect before starting the server.
*
* @param integer $port Port to bind to
*/
public function setPort($port) {
$this->port = $port;
}
/**
* Returns array of connected clients
*
* @return SocketClient[] Array of connected clients
*/
public function getClients() {
return $this->clients;
}
/**
* Returns the number of connected clients
*
* @return integer Number of clients
*/
public function getClientCount() {
return count($this->clients);
}
/**
* Returns last socket error as an object.
*
* The object is a basic stdClass with parameters:
* - code: the code of the error
* - message: translated error code as message
*
* @param resource $socket Optional socket resource
* @return stdClass Error as stdClass instance with fields code and message
*/
public static function getLastError($socket = null) {
$lastErrorCode = socket_last_error($socket);
$lastErrorMessage = socket_strerror($lastErrorCode);
$error = new stdClass();
$error->code = $lastErrorCode;
$error->message = $lastErrorMessage;
return $error;
}
/**
* Starts the server by binding to a port
*
* @param integer $maxConnections Max number of incoming backlog connections
* @throws Exception If something goes wrong
*/
public function start($maxConnections = SOMAXCONN) {
set_time_limit(0);
ob_implicit_flush();
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->socket === false) {
$error = self::getLastError();
throw new Exception(
'Creating socket failed: '.$error->message.' ['.$error->code.']'
);
}
$this->sockets[] = $this->socket;
if (
socket_set_option(
$this->socket,
SOL_SOCKET,
SO_REUSEADDR,
1
) === false
) {
$error = self::getLastError($this->socket);
throw new Exception(
'Setting socket option to reuse address to true failed: '.
$error->message.' ['.$error->code.']'
);
}
if (socket_bind($this->socket, $this->host, $this->port) === false) {
$error = self::getLastError($this->socket);
throw new Exception(
'Binding to port '.$this->port.' on host "'.$this->host.
'" failed: '.$error->message.' ['.$error->code.']'
);
}
if (socket_listen($this->socket, $maxConnections) === false) {
$error = self::getLastError($this->socket);
throw new Exception(
'Starting to listen on the socket on port '.$this->port.
' and host "'.$this->host.'" failed: '.$error->message.
' ['.$error->code.']'
);
}
$this->run();
}
/**
* Runs the server as an infinite loop
*
* @return void
*/
protected function run() {
while (true) {
$changedSockets = $this->sockets;
$write = $except = $tv = $tvu = null;
$result = socket_select(
$changedSockets,
$write,
$except,
$tv,
$tvu
);
if ($result === false) {
socket_close($this->socket);
$error = self::getLastError($this->socket);
throw new Exception(
'Checking for changed sockets failed: '.$error->message.
' ['.$error->code.']'
);
}
foreach ($changedSockets as $socket) {
if ($socket == $this->socket) {
$newSocket = socket_accept($this->socket);
if ($newSocket !== false) {
$this->connectClient($newSocket);
} else {
$error = self::getLastError($this->socket);
trigger_error(
'Failed to accept incoming client: '.
$error->message.' ['.$error->code.']',
E_USER_WARNING
);
}
} else {
$client = $this->getClientBySocket($socket);
if (!isset($client)) {
trigger_error(
'Failed to match given socket to client',
E_USER_WARNING
);
socket_close($socket);
continue;
}
$buffer = '';
$message = '';
$bytes = @socket_recv($socket, $buffer, 4096, 0);
if ($bytes === false) {
$error = self::getLastError($this->socket);
trigger_error(
'Failed to receive data from client #'.$client->id.': '.
$error->message.' ['.$error->code.']',
E_USER_WARNING
);
continue;
}
$len = ord($buffer[1]) & 127;
$masks = null;
$data = null;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
} else if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
for ($index = 0; $index < strlen($data); $index++) {
$message .= $data[$index] ^ $masks[$index % 4];
}
if ($bytes == 0) {
$this->disconnectClient($socket);
} else {
if ($client->state == SocketClient::STATE_OPEN) {
$client->lastRecieveTime = time();
$this->log('< ['.$client->id.'] '.$message);
foreach ($this->listeners as $listener) {
$listener->onMessageRecieved(
$this,
$client,
$message
);
}
} else if ($client->state == SocketClient::STATE_CONNECTING) {
$client->performHandshake($buffer);
}
}
}
}
}
}
/**
* Connects a client by socket.
*
* Creates a new instance of the SocketClient class and adds it to the list
* of clients. Also adds the socket to the list of sockets.
*
* @param resource $socket Socket to use
*/
protected function connectClient($socket) {
$client = new SocketClient($this, $socket);
$this->clients[] = $client;
$this->sockets[] = $socket;
$this->log('+ ['.$client->id.'] connected');
foreach ($this->listeners as $listener) {
$listener->onClientConnected(
$this,
$client
);
}
}
/**
* Disconnects a client by socket.
*
* @param resource $clientSocket Socket to use
*/
protected function disconnectClient($clientSocket) {
foreach ($this->sockets as $socketKey => $socket) {
if ($socket === $clientSocket) {
socket_close($client->socket);
unset($this->sockets[$socketKey]);
}
}
foreach ($this->clients as $clientKey => $client) {
if ($client->socket === $clientSocket) {
$this->log('- ['.$client->id.'] client disconnected');
foreach ($this->listeners as $listener) {
$listener->onClientDisconnected(
$this,
$client
);
}
$this->clients[$clientKey]->state = SocketClient::STATE_CLOSED;
unset($this->clients[$clientKey]);
}
}
}
/**
* Returns client by socket reference.
*
* @param resource $socket Socket resource
* @return SocketClient The client on the socket or null if not found
*/
protected function getClientBySocket($socket) {
foreach ($this->clients as $client) {
if ($client->socket == $socket) {
return $client;
}
}
return null;
}
/**
* Sends a message to given socket
*
* @param resource $socket Socket to send the message to
* @param mixed $message Message to send
* @param integer $bufferSize Buffer size to use
* @throws Exception If something goes wrong
*/
public function send(
$socket,
$message,
$bufferSize = 4096
) {
$opcode = self::OPCODE_TEXT;
if (is_object($message)) {
$message = (string)$message;
}
// fetch message length
$messageLength = strlen($message);
// work out amount of frames to send, based on $bufferSize
$frameCount = ceil($messageLength / $bufferSize);
if ($frameCount == 0) $frameCount = 1;
// set last frame variables
$maxFrame = $frameCount - 1;
$lastFrameBufferLength = ($messageLength % $bufferSize) != 0 ? ($messageLength % $bufferSize) : ($messageLength != 0 ? $bufferSize : 0);
// loop around all frames to send
for ($i=0; $i<$frameCount; $i++) {
// fetch fin, opcode and buffer length for frame
$fin = $i != $maxFrame ? 0 : self::FIN;
$opcode = $i != 0 ? self::OPCODE_CONTINUATION : $opcode;
$bufferLength = $i != $maxFrame ? $bufferSize : $lastFrameBufferLength;
// set payload length variables for frame
if ($bufferLength <= 125) {
$payloadLength = $bufferLength;
$payloadLengthExtended = '';
$payloadLengthExtendedLength = 0;
}
elseif ($bufferLength <= 65535) {
$payloadLength = self::PAYLOAD_LENGTH_16;
$payloadLengthExtended = pack('n', $bufferLength);
$payloadLengthExtendedLength = 2;
}
else {
$payloadLength = self::PAYLOAD_LENGTH_63;
$payloadLengthExtended = pack('xxxxN', $bufferLength); // pack 32 bit int, should really be 64 bit int
$payloadLengthExtendedLength = 8;
}
// set frame bytes
$buffer = pack('n', (($fin | $opcode) << 8) | $payloadLength) . $payloadLengthExtended . substr($message, $i*$bufferSize, $bufferLength);
// send frame
$socket = $socket;
$left = 2 + $payloadLengthExtendedLength + $bufferLength;
do {
$sent = @socket_send($socket, $buffer, $left, 0);
if ($sent === false) return false;
$left -= $sent;
if ($sent > 0) $buffer = substr($buffer, $sent);
}
while ($left > 0);
}
$client = $this->getClientBySocket($socket);
$clientId = -1;
if ($client != null) {
$client->lastSendTime = time();
$clientId = $client->id;
}
$this->log('> ['.$clientId.'] '.$message);
return true;
}
/**
* Logs a message to console
*
* @param string $message Message to log
*/
public function log($message) {
foreach ($this->listeners as $listener) {
$listener->onLogMessage(
$this,
$message
);
}
}
}
/**
* Class representing a WebSocket client.
*/
class SocketClient {
/**
* Number of instances created.
*
* @var integer
*/
static $instances = 0;
/**
* Reference to server that created the client.
*
* @var SocketServer
*/
public $server;
/**
* Client id.
*
* This starts from one and is incremented for every connecting user.
*
* @var integer
*/
public $id;
/**
* Client socket.
*
* @var resource
*/
public $socket;
/**
* Client state.
*
* One of SocketClient::STATE_.. constants.
*
* @var integer
*/
public $state;
/**
* The ip of the client.
*
* @var string
*/
public $ip;
/**
* The port of the client.
*
* @var integer
*/
public $port;
/**
* The time data was last recieved from the client.
*
* @var integer
*/
public $lastRecieveTime = 0;
/**
* Last time data was sent to this client.
*
* @var integer
*/
public $lastSendTime = 0;
/**
* Any data associated with the user.
*
* @var mixed
*/
public $data = array();
/**
* User is connecting, handshake not yet performed.
*/
const STATE_CONNECTING = 0;
/**
* Connection is valid.
*/
const STATE_OPEN = 1;
/**
* Connection has been closed.
*/
const STATE_CLOSED = 2;
/**
* Constructor, sets the server that spawned the client and the socket.
*
* @param SocketServer $server Parent server
* @param resource $socket User socket
* @param integer $state Initial state
*/
public function __construct(
SocketServer $server,
$socket,
$state = self::STATE_CONNECTING
) {
self::$instances++;
$this->server = $server;
$this->id = self::$instances;
$this->socket = $socket;
$this->state = $state;
$this->lastRecieveTime = time();
socket_getpeername($socket, $this->ip, $this->port);
}
/**
* Sends a message to the client
*
* @param mixed $message Message to send
*/
public function send($message) {
if ($this->state == self::STATE_CLOSED) {
throw new Exception(
'Unable to send message, connection has been closed'
);
}
$this->server->send($this->socket, $message);
}
/**
* Sets client property.
*
* @param string $name Property name
* @param mixed $value Property value
*/
public function set($name, $value) {
$this->data[$name] = $value;
}
/**
* Returns client property.
*
* @param string $name Name of the property
* @param mixed $default Default value returned when property does not exist
* @return mixed
*/
public function get($name, $default = null) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
} else {
return $default;
}
}
/**
* Disconnects the client.
*/
public function disconnect() {
if ($this->state == self::STATE_CLOSED) {
return;
}
$this->server->disconnectClient($this->socket);
}
/**
* Does the magic handshake to begin the connection
*
* @param string $buffer Buffer sent by the client
* @return bool Was the handshake successful
* @throws Exception If something goes wrong
*/
public function performHandshake($buffer) {
if ($this->state != self::STATE_CONNECTING) {
throw new Exception(
'Unable to perform handshake, client is not in connecting state'
);
}
$headers = $this->parseRequestHeader($buffer);
$key = $headers['Sec-WebSocket-Key'];
$hash = base64_encode(
sha1($key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)
);
$headers = array(
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
'Sec-WebSocket-Accept: '.$hash
);
$headers = implode("\r\n", $headers)."\r\n\r\n";
$left = strlen($headers);
do {
$sent = @socket_send($this->socket, $headers, $left, 0);
if ($sent === false) {
$error = $this->server->getLastError();
throw new Exception(
'Sending handshake failed: : '.$error->message.
' ['.$error->code.']'
);
}
$left -= $sent;
if ($sent > 0) {
$headers = substr($headers, $sent);
}
}
while ($left > 0);
$this->state = self::STATE_OPEN;
}
/**
* Parses the request header into resource, headers and security code
*
* @param string $request The request
* @return array Array containing the resource, headers and security code
*/
private function parseRequestHeader($request) {
$headers = array();
foreach (explode("\r\n", $request) as $line) {
if (strpos($line, ': ') !== false) {
list($key, $value) = explode(': ', $line);
$headers[trim($key)] = trim($value);
}
}
return $headers;
}
}