WebsocketClient.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: phperstar
  5. * Date: 2020/11/6
  6. * Time: 10:22 AM
  7. */
  8. namespace Mall\Framework\Swoole;
  9. use Mall\Framework\Swoole\WebsocketClient\Parser;
  10. use Mall\Framework\Swoole\WebsocketClient\WebsocketParser;
  11. class WebSocketClient
  12. {
  13. const VERSION = '0.1.4';
  14. const TOKEN_LENGHT = 16;
  15. const TYPE_ID_WELCOME = 0;
  16. const TYPE_ID_PREFIX = 1;
  17. const TYPE_ID_CALL = 2;
  18. const TYPE_ID_CALLRESULT = 3;
  19. const TYPE_ID_ERROR = 4;
  20. const TYPE_ID_SUBSCRIBE = 5;
  21. const TYPE_ID_UNSUBSCRIBE = 6;
  22. const TYPE_ID_PUBLISH = 7;
  23. const TYPE_ID_EVENT = 8;
  24. protected $key;
  25. protected $host;
  26. protected $port;
  27. protected $path;
  28. /**
  29. * @var TCP
  30. */
  31. protected $socket;
  32. protected $buffer = '';
  33. /**
  34. * @var bool
  35. */
  36. protected $connected = false;
  37. protected $handshake = false;
  38. protected $ssl = false;
  39. protected $ssl_key_file;
  40. protected $ssl_cert_file;
  41. protected $haveSwooleEncoder = false;
  42. protected $header;
  43. const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
  44. const UserAgent = 'SwooleWebsocketClient';
  45. /**
  46. * @param string $host
  47. * @param int $port
  48. * @param string $path
  49. * @throws \Exception
  50. */
  51. function __construct($options, $path = '/')
  52. {
  53. if (empty($options))
  54. {
  55. throw new \Exception("联系webstock服务端配置为空");
  56. }
  57. $this->haveSwooleEncoder = method_exists('swoole_websocket_server', 'pack');
  58. $this->host = $options['host'];
  59. $this->port = $options['port'];
  60. $this->path = $path;
  61. $this->key = $this->generateToken(self::TOKEN_LENGHT);
  62. $this->parser = new WebsocketParser();
  63. if($options['ssl'] == true){
  64. self::enableCrypto($options['ssl_key_file'], $options['ssl_cert_file']);
  65. }
  66. if(!self::connect(isset($options['time_out'])?$options['time_out']:0.5)){
  67. throw new \Exception("connect failed. Error:".$this->socket->errCode.PHP_EOL);
  68. }
  69. }
  70. /**
  71. * @param string $keyFile
  72. * @param string $certFile
  73. * @throws Swoole\Http\\Exception
  74. */
  75. function enableCrypto($keyFile = '', $certFile = '')
  76. {
  77. if (!extension_loaded('swoole'))
  78. {
  79. throw new \Exception("require swoole extension.");
  80. }
  81. $this->ssl = true;
  82. $this->ssl_key_file = $keyFile;
  83. $this->ssl_cert_file = $certFile;
  84. }
  85. /**
  86. * Disconnect on destruct
  87. */
  88. function __destruct()
  89. {
  90. if ($this->connected)
  91. {
  92. $this->disconnect();
  93. }
  94. }
  95. /**
  96. * Connect client to server
  97. * @param $timeout
  98. * @return $this
  99. */
  100. public function connect($timeout = 0.5)
  101. {
  102. if (extension_loaded('swoole'))
  103. {
  104. $type = SWOOLE_TCP;
  105. if ($this->ssl)
  106. {
  107. $type |= SWOOLE_SSL;
  108. }
  109. $this->socket = new \swoole_client($type);
  110. if ($this->ssl_key_file)
  111. {
  112. var_dump($this->ssl_key_file);
  113. var_dump(file_exists($this->ssl_key_file));
  114. var_dump(file_exists($this->ssl_cert_file));
  115. $this->socket->set(array(
  116. 'ssl_key_file' => $this->ssl_key_file,
  117. 'ssl_cert_file' => $this->ssl_cert_file,
  118. /*'open_length_check' => true, // 开启协议解析
  119. 'package_length_type' => 'N', // 长度字段的类型
  120. 'package_length_offset' => 0, //第几个字节是包长度的值
  121. 'package_body_offset' => PACKAGE_BODY_OFFSET, //第几个字节开始计算包内容
  122. 'package_max_length' => PACKAGE_MAXLENG, //协议最大长度*/
  123. ));
  124. var_dump($this->socket);
  125. }
  126. }
  127. else
  128. {
  129. $this->socket = new \TCP;
  130. }
  131. //建立连接
  132. if (!$this->socket->connect($this->host, $this->port, $timeout))
  133. {
  134. return false;
  135. }
  136. $this->connected = true;
  137. //WebSocket握手
  138. if ($this->socket->send($this->createHeader()) === false)
  139. {
  140. return false;
  141. }
  142. $headerBuffer = '';
  143. while(true)
  144. {
  145. $_tmp = $this->socket->recv();
  146. if ($_tmp)
  147. {
  148. $headerBuffer .= $_tmp;
  149. if (substr($headerBuffer, -4, 4) != "\r\n\r\n")
  150. {
  151. continue;
  152. }
  153. }
  154. else
  155. {
  156. return false;
  157. }
  158. return $this->doHandShake($headerBuffer);
  159. }
  160. return false;
  161. }
  162. /**
  163. * 握手
  164. * @param $headerBuffer
  165. * @return bool
  166. */
  167. function doHandShake($headerBuffer)
  168. {
  169. $header = Parser::parseHeader($headerBuffer);
  170. if (!isset($header['Sec-WebSocket-Accept']))
  171. {
  172. $this->disconnect();
  173. return false;
  174. }
  175. if ($header['Sec-WebSocket-Accept'] != base64_encode(pack('H*', sha1($this->key . self::GUID))))
  176. {
  177. $this->disconnect();
  178. return false;
  179. }
  180. $this->handshake = true;
  181. $this->header = $header;
  182. return true;
  183. }
  184. /**
  185. * Disconnect from server
  186. */
  187. public function disconnect()
  188. {
  189. $this->connected = false;
  190. $this->socket->close();
  191. }
  192. /**
  193. * 接收数据
  194. * @return bool | Swoole\Http\WebSocketFrame
  195. * @throws Swoole\Http\\Exception
  196. */
  197. function recv()
  198. {
  199. if (!$this->handshake)
  200. {
  201. trigger_error("not complete handshake.");
  202. return false;
  203. }
  204. while (true)
  205. {
  206. $data = $this->socket->recv();
  207. if (!$data)
  208. {
  209. return false;
  210. }
  211. $this->parser->push($data);
  212. $frame = $this->parser->pop($data);
  213. if ($frame)
  214. {
  215. return $frame->data;
  216. }
  217. }
  218. return false;
  219. }
  220. /**
  221. * send string data
  222. * @param $data
  223. * @param string $type
  224. * @param bool $masked
  225. * @throws \Exception
  226. * @return bool
  227. */
  228. public function send($data, $type = 'text', $masked = true)
  229. {
  230. if (empty($data))
  231. {
  232. throw new \Exception("data is empty");
  233. }
  234. if (!$this->handshake)
  235. {
  236. trigger_error("not complete handshake.");
  237. return false;
  238. }
  239. if ($this->haveSwooleEncoder)
  240. {
  241. switch($type)
  242. {
  243. case 'text':
  244. $_type = WEBSOCKET_OPCODE_TEXT;
  245. break;
  246. case 'binary':
  247. case 'bin':
  248. $_type = WEBSOCKET_OPCODE_BINARY;
  249. break;
  250. default:
  251. return false;
  252. }
  253. $_send = \swoole_websocket_server::pack($data, $_type);
  254. }
  255. else
  256. {
  257. $_send = $this->hybi10Encode($data, $type, $masked);
  258. }
  259. return $this->socket->send($_send);
  260. }
  261. /**
  262. * send json object
  263. * @param $data
  264. * @param bool $masked
  265. * @return bool
  266. */
  267. function sendJson($data, $masked = true)
  268. {
  269. return $this->send(json_encode($data, JSON_UNESCAPED_UNICODE).PACKAGE_EOF, 'text', $masked);
  270. }
  271. /**
  272. * Create header for websocket client
  273. * @return string
  274. */
  275. final protected function createHeader()
  276. {
  277. $host = $this->host;
  278. if ($host === '127.0.0.1' || $host === '0.0.0.0')
  279. {
  280. $host = 'localhost';
  281. }
  282. return "GET {$this->path} HTTP/1.1" . "\r\n" .
  283. "Origin: null" . "\r\n" .
  284. "Host: {$host}:{$this->port}" . "\r\n" .
  285. "Sec-WebSocket-Key: {$this->key}" . "\r\n" .
  286. "User-Agent: ".self::UserAgent."/" . self::VERSION . "\r\n" .
  287. "Upgrade: Websocket" . "\r\n" .
  288. "Connection: Upgrade" . "\r\n" .
  289. "Sec-WebSocket-Protocol: wamp" . "\r\n" .
  290. "Sec-WebSocket-Version: 13" . "\r\n" . "\r\n";
  291. }
  292. /**
  293. * Parse raw incoming data
  294. *
  295. * @param $header
  296. * @return array
  297. */
  298. final protected function parseIncomingRaw($header)
  299. {
  300. $retval = array();
  301. $content = "";
  302. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
  303. foreach ($fields as $field) {
  304. if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
  305. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function ($matches) {
  306. return strtoupper($matches[0]);
  307. }, strtolower(trim($match[1])));
  308. if (isset($retval[$match[1]])) {
  309. $retval[$match[1]] = array($retval[$match[1]], $match[2]);
  310. } else {
  311. $retval[$match[1]] = trim($match[2]);
  312. }
  313. } else if (preg_match('!HTTP/1\.\d (\d)* .!', $field)) {
  314. $retval["status"] = $field;
  315. } else {
  316. $content .= $field . "\r\n";
  317. }
  318. }
  319. $retval['content'] = $content;
  320. return $retval;
  321. }
  322. /**
  323. * Generate token
  324. *
  325. * @param int $length
  326. * @return string
  327. */
  328. private function generateToken($length)
  329. {
  330. $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
  331. $useChars = array();
  332. // select some random chars:
  333. for ($i = 0; $i < $length; $i++) {
  334. $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
  335. }
  336. // Add numbers
  337. array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
  338. shuffle($useChars);
  339. $randomString = trim(implode('', $useChars));
  340. $randomString = substr($randomString, 0, self::TOKEN_LENGHT);
  341. return base64_encode($randomString);
  342. }
  343. /**
  344. * Generate token
  345. *
  346. * @param int $length
  347. * @return string
  348. */
  349. public function generateAlphaNumToken($length)
  350. {
  351. $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
  352. srand((float)microtime() * 1000000);
  353. $token = '';
  354. do
  355. {
  356. shuffle($characters);
  357. $token .= $characters[mt_rand(0, (count($characters) - 1))];
  358. } while (strlen($token) < $length);
  359. return $token;
  360. }
  361. /**
  362. * @param $payload
  363. * @param string $type
  364. * @param bool $masked
  365. * @return bool|string
  366. */
  367. private function hybi10Encode($payload, $type = 'text', $masked = true)
  368. {
  369. $frameHead = array();
  370. $payloadLength = strlen($payload);
  371. switch ($type)
  372. {
  373. //文本内容
  374. case 'text':
  375. // first byte indicates FIN, Text-Frame (10000001):
  376. $frameHead[0] = 129;
  377. break;
  378. //二进制内容
  379. case 'binary':
  380. case 'bin':
  381. // first byte indicates FIN, Text-Frame (10000010):
  382. $frameHead[0] = 130;
  383. break;
  384. case 'close':
  385. // first byte indicates FIN, Close Frame(10001000):
  386. $frameHead[0] = 136;
  387. break;
  388. case 'ping':
  389. // first byte indicates FIN, Ping frame (10001001):
  390. $frameHead[0] = 137;
  391. break;
  392. case 'pong':
  393. // first byte indicates FIN, Pong frame (10001010):
  394. $frameHead[0] = 138;
  395. break;
  396. }
  397. // set mask and payload length (using 1, 3 or 9 bytes)
  398. if ($payloadLength > 65535)
  399. {
  400. $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
  401. $frameHead[1] = ($masked === true) ? 255 : 127;
  402. for ($i = 0; $i < 8; $i++)
  403. {
  404. $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
  405. }
  406. // most significant bit MUST be 0 (close connection if frame too big)
  407. if ($frameHead[2] > 127)
  408. {
  409. $this->socket->close();
  410. return false;
  411. }
  412. }
  413. elseif ($payloadLength > 125)
  414. {
  415. $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
  416. $frameHead[1] = ($masked === true) ? 254 : 126;
  417. $frameHead[2] = bindec($payloadLengthBin[0]);
  418. $frameHead[3] = bindec($payloadLengthBin[1]);
  419. }
  420. else
  421. {
  422. $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
  423. }
  424. // convert frame-head to string:
  425. foreach (array_keys($frameHead) as $i)
  426. {
  427. $frameHead[$i] = chr($frameHead[$i]);
  428. }
  429. // generate a random mask:
  430. $mask = array();
  431. if ($masked === true)
  432. {
  433. for ($i = 0; $i < 4; $i++)
  434. {
  435. $mask[$i] = chr(rand(0, 255));
  436. }
  437. $frameHead = array_merge($frameHead, $mask);
  438. }
  439. $frame = implode('', $frameHead);
  440. // append payload to frame:
  441. for ($i = 0; $i < $payloadLength; $i++)
  442. {
  443. $frame .= $masked ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
  444. }
  445. return $frame;
  446. }
  447. /**
  448. * @param $data
  449. * @return string
  450. * @throws \Exception
  451. */
  452. private function hybi10Decode($data)
  453. {
  454. if (empty($data))
  455. {
  456. throw new \Exception("data is empty");
  457. }
  458. $bytes = $data;
  459. $secondByte = sprintf('%08b', ord($bytes[1]));
  460. $masked = ($secondByte[0] == '1') ? true : false;
  461. $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
  462. //服务器不会设置mask
  463. if ($dataLength === 126)
  464. {
  465. $decodedData = substr($bytes, 4);
  466. }
  467. elseif ($dataLength === 127)
  468. {
  469. $decodedData = substr($bytes, 10);
  470. }
  471. else
  472. {
  473. $decodedData = substr($bytes, 2);
  474. }
  475. exit("len=".$dataLength."\n");
  476. return $decodedData;
  477. }
  478. }