Aucune description

websocket_client.class.php 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. /**
  3. * Very basic websocket client.
  4. * Supporting draft hybi-10.
  5. *
  6. * @author Simon Samtleben <web@lemmingzshadow.net>
  7. * @version 2011-10-18
  8. */
  9. class WebsocketClient
  10. {
  11. private $_host;
  12. private $_port;
  13. private $_path;
  14. private $_origin;
  15. private $_Socket = null;
  16. private $_connected = false;
  17. public function __construct() { }
  18. public function __destruct()
  19. {
  20. $this->disconnect();
  21. }
  22. public function sendData($data, $type = 'text', $masked = true)
  23. {
  24. if($this->_connected === false)
  25. {
  26. //trigger_error("Not connected", E_USER_WARNING);
  27. return false;
  28. }
  29. if( !is_string($data)) {
  30. //trigger_error("Not a string data was given.", E_USER_WARNING);
  31. return false;
  32. }
  33. if (strlen($data) == 0)
  34. {
  35. return false;
  36. }
  37. $res = @fwrite($this->_Socket, $this->_hybi10Encode($data, $type, $masked));
  38. if($res === 0 || $res === false)
  39. {
  40. return false;
  41. }
  42. $buffer = ' ';
  43. // while($buffer !== '')
  44. // {
  45. // $buffer = fread($this->_Socket,2);// drop?
  46. // echo($buffer);
  47. // }
  48. return $buffer;
  49. }
  50. function getS($n){
  51. return fread($this->_Socket,$n);
  52. }
  53. public function connect($host, $port, $path, $origin = false)
  54. {
  55. $this->_host = $host;
  56. $this->_port = $port;
  57. $this->_path = $path;
  58. $this->_origin = $origin;
  59. $key = base64_encode($this->_generateRandomString(16, false, true));
  60. $header = "GET " . $path . " HTTP/1.1\r\n";
  61. $header.= "Host: ".$host.":".$port."\r\n";
  62. $header.= "Upgrade: websocket\r\n";
  63. $header.= "Pragma: no-cache\r\n";
  64. $header.= "Cache-Control: no-cache\r\n";
  65. $header.= "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\n";
  66. $header.= "Accept-Encoding: gzip, deflate, sdch\r\n";
  67. $header.= "Accept-Language: zh-CN,zh;q=0.8\r\n";
  68. $header.= "Origin: " . $origin . "\r\n";
  69. $header.= "Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n";
  70. $header.= "Connection: Upgrade\r\n";
  71. $header.= "Sec-WebSocket-Key: " . $key . "\r\n";
  72. //if($origin !== false)
  73. //{
  74. $header.= "Sec-WebSocket-Origin: " . $origin . "\r\n";
  75. //}
  76. $header.= "Sec-WebSocket-Version: 13\r\n\r\n";
  77. $this->_Socket = fsockopen($host, $port, $errno, $errstr, 30);
  78. //socket_set_timeout($this->_Socket, 0, 10000);
  79. @fwrite($this->_Socket, $header);
  80. $response = @fread($this->_Socket, 1500);
  81. preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $response, $matches);
  82. if ($matches) {
  83. $keyAccept = trim($matches[1]);
  84. $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
  85. $this->_connected = ($keyAccept === $expectedResonse) ? true : false;
  86. }
  87. return $this->_connected;
  88. }
  89. public function checkConnection()
  90. {
  91. $this->_connected = false;
  92. // send ping:
  93. $data = 'ping?';
  94. @fwrite($this->_Socket, $this->_hybi10Encode($data, 'ping', true));
  95. $response = @fread($this->_Socket, 300);
  96. if(empty($response))
  97. {
  98. return false;
  99. }
  100. $response = $this->_hybi10Decode($response);
  101. if(!is_array($response))
  102. {
  103. return false;
  104. }
  105. if(!isset($response['type']) || $response['type'] !== 'pong')
  106. {
  107. return false;
  108. }
  109. $this->_connected = true;
  110. return true;
  111. }
  112. public function disconnect()
  113. {
  114. $this->_connected = false;
  115. is_resource($this->_Socket) and fclose($this->_Socket);
  116. }
  117. public function reconnect()
  118. {
  119. sleep(10);
  120. $this->_connected = false;
  121. fclose($this->_Socket);
  122. $this->connect($this->_host, $this->_port, $this->_path, $this->_origin);
  123. }
  124. private function _generateRandomString($length = 10, $addSpaces = true, $addNumbers = true)
  125. {
  126. $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
  127. $useChars = array();
  128. // select some random chars:
  129. for($i = 0; $i < $length; $i++)
  130. {
  131. $useChars[] = $characters[mt_rand(0, strlen($characters)-1)];
  132. }
  133. // add spaces and numbers:
  134. if($addSpaces === true)
  135. {
  136. array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
  137. }
  138. if($addNumbers === true)
  139. {
  140. array_push($useChars, rand(0,9), rand(0,9), rand(0,9));
  141. }
  142. shuffle($useChars);
  143. $randomString = trim(implode('', $useChars));
  144. $randomString = substr($randomString, 0, $length);
  145. return $randomString;
  146. }
  147. private function _hybi10Encode($payload, $type = 'text', $masked = true)
  148. {
  149. $frameHead = array();
  150. $frame = '';
  151. $payloadLength = strlen($payload);
  152. switch($type)
  153. {
  154. case 'text':
  155. // first byte indicates FIN, Text-Frame (10000001):
  156. $frameHead[0] = 129;
  157. break;
  158. case 'close':
  159. // first byte indicates FIN, Close Frame(10001000):
  160. $frameHead[0] = 136;
  161. break;
  162. case 'ping':
  163. // first byte indicates FIN, Ping frame (10001001):
  164. $frameHead[0] = 137;
  165. break;
  166. case 'pong':
  167. // first byte indicates FIN, Pong frame (10001010):
  168. $frameHead[0] = 138;
  169. break;
  170. }
  171. // set mask and payload length (using 1, 3 or 9 bytes)
  172. if($payloadLength > 65535)
  173. {
  174. $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
  175. $frameHead[1] = ($masked === true) ? 255 : 127;
  176. for($i = 0; $i < 8; $i++)
  177. {
  178. $frameHead[$i+2] = bindec($payloadLengthBin[$i]);
  179. }
  180. // most significant bit MUST be 0 (close connection if frame too big)
  181. if($frameHead[2] > 127)
  182. {
  183. $this->close(1004);
  184. return false;
  185. }
  186. }
  187. elseif($payloadLength > 125)
  188. {
  189. $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
  190. $frameHead[1] = ($masked === true) ? 254 : 126;
  191. $frameHead[2] = bindec($payloadLengthBin[0]);
  192. $frameHead[3] = bindec($payloadLengthBin[1]);
  193. }
  194. else
  195. {
  196. $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
  197. }
  198. // convert frame-head to string:
  199. foreach(array_keys($frameHead) as $i)
  200. {
  201. $frameHead[$i] = chr($frameHead[$i]);
  202. }
  203. if($masked === true)
  204. {
  205. // generate a random mask:
  206. $mask = array();
  207. for($i = 0; $i < 4; $i++)
  208. {
  209. $mask[$i] = chr(rand(0, 255));
  210. }
  211. $frameHead = array_merge($frameHead, $mask);
  212. }
  213. $frame = implode('', $frameHead);
  214. // append payload to frame:
  215. $framePayload = array();
  216. for($i = 0; $i < $payloadLength; $i++)
  217. {
  218. $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
  219. }
  220. return $frame;
  221. }
  222. private function _hybi10Decode($data)
  223. {
  224. $payloadLength = '';
  225. $mask = '';
  226. $unmaskedPayload = '';
  227. $decodedData = array();
  228. // estimate frame type:
  229. $firstByteBinary = sprintf('%08b', ord($data[0]));
  230. $secondByteBinary = sprintf('%08b', ord($data[1]));
  231. $opcode = bindec(substr($firstByteBinary, 4, 4));
  232. $isMasked = ($secondByteBinary[0] == '1') ? true : false;
  233. $payloadLength = ord($data[1]) & 127;
  234. switch($opcode)
  235. {
  236. // text frame:
  237. case 1:
  238. $decodedData['type'] = 'text';
  239. break;
  240. case 2:
  241. $decodedData['type'] = 'binary';
  242. break;
  243. // connection close frame:
  244. case 8:
  245. $decodedData['type'] = 'close';
  246. break;
  247. // ping frame:
  248. case 9:
  249. $decodedData['type'] = 'ping';
  250. break;
  251. // pong frame:
  252. case 10:
  253. $decodedData['type'] = 'pong';
  254. break;
  255. default:
  256. return false;
  257. break;
  258. }
  259. if($payloadLength === 126)
  260. {
  261. $mask = substr($data, 4, 4);
  262. $payloadOffset = 8;
  263. $dataLength = bindec(sprintf('%08b', ord($data[2])) . sprintf('%08b', ord($data[3]))) + $payloadOffset;
  264. }
  265. elseif($payloadLength === 127)
  266. {
  267. $mask = substr($data, 10, 4);
  268. $payloadOffset = 14;
  269. $tmp = '';
  270. for($i = 0; $i < 8; $i++)
  271. {
  272. $tmp .= sprintf('%08b', ord($data[$i+2]));
  273. }
  274. $dataLength = bindec($tmp) + $payloadOffset;
  275. unset($tmp);
  276. }
  277. else
  278. {
  279. $mask = substr($data, 2, 4);
  280. $payloadOffset = 6;
  281. $dataLength = $payloadLength + $payloadOffset;
  282. }
  283. if($isMasked === true)
  284. {
  285. for($i = $payloadOffset; $i < $dataLength; $i++)
  286. {
  287. $j = $i - $payloadOffset;
  288. if(isset($data[$i]))
  289. {
  290. $unmaskedPayload .= $data[$i] ^ $mask[$j % 4];
  291. }
  292. }
  293. $decodedData['payload'] = $unmaskedPayload;
  294. }
  295. else
  296. {
  297. $payloadOffset = $payloadOffset - 4;
  298. $decodedData['payload'] = substr($data, $payloadOffset);
  299. }
  300. return $decodedData;
  301. }
  302. }