-
Notifications
You must be signed in to change notification settings - Fork 26
/
RtmpSocket.class.php
97 lines (86 loc) · 1.84 KB
/
RtmpSocket.class.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
<?php
class RtmpSocket
{
private $host;
private $port;
private $socket;
public $timeout = 15;
public function __construct()
{
}
/**
* Init socket
*
* @return bool
*/
public function connect($host, $port)
{
$this->close();
$this->host = $host;
$this->port = $port;
if (($this->socket = socket_create(AF_INET, SOCK_STREAM, 0)) == false)
throw new Exception("Unable to create socket.");
if (!socket_connect($this->socket, $this->host, $this->port))
throw new Exception("Could not connect to $this->host:$this->port");
return $this->socket != null;
}
/**
* Close socket
*
*/
public function close()
{
$this->socket && socket_close($this->socket);
}
/**
* Read socket
*
* @param int $length
* @return RtmpStream
*/
public function read($length)
{
$buff = "";
$t = time();
do
{
$recv = "";
$recv = socket_read($this->socket, $length - strlen($buff), PHP_BINARY_READ);
if($recv === false)
throw new Exception("Could not read socket");
if($recv != "")
$buff .= $recv;
if(time() > $t + $this->timeout)
throw new Exception("Timeout, could not read socket");
}
while($recv != "" && strlen($buff) < $length);
$this->recvBuffer = substr($buff,$length);
return new RtmpStream(substr($buff,0,$length));
}
/**
* Write data
*
* @param RtmpStream $data
* @param int $n
* @return bool
*/
public function write(RtmpStream $data, $n = -1)
{
$buffer = $data->flush($n);
$n = strlen($buffer);
while($n>0)
{
$nBytes = socket_write($this->socket,$buffer,$n);
if($nBytes === false)
{
$this->close();
return false;
}
if($nBytes == 0)
break;
$n -= $nBytes;
$buffer = substr($buffer, $nBytes);
}
return true;
}
}