WebsocketClient.Class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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(file_exists($this->ssl_key_file));
  113. var_dump(file_exists($this->ssl_cert_file));
  114. $this->socket->set(array(
  115. 'ssl_key_file' => $this->ssl_key_file,
  116. 'ssl_cert_file' => $this->ssl_cert_file,
  117. /*'open_length_check' => true, // 开启协议解析
  118. 'package_length_type' => 'N', // 长度字段的类型
  119. 'package_length_offset' => 0, //第几个字节是包长度的值
  120. 'package_body_offset' => PACKAGE_BODY_OFFSET, //第几个字节开始计算包内容
  121. 'package_max_length' => PACKAGE_MAXLENG, //协议最大长度*/
  122. ));
  123. var_dump($this->socket);
  124. }
  125. }
  126. else
  127. {
  128. $this->socket = new \TCP;
  129. }
  130. //建立连接
  131. if (!$this->socket->connect($this->host, $this->port, $timeout))
  132. {
  133. return false;
  134. }
  135. $this->connected = true;
  136. //WebSocket握手
  137. if ($this->socket->send($this->createHeader()) === false)
  138. {
  139. return false;
  140. }
  141. $headerBuffer = '';
  142. while(true)
  143. {
  144. $_tmp = $this->socket->recv();
  145. if ($_tmp)
  146. {
  147. $headerBuffer .= $_tmp;
  148. if (substr($headerBuffer, -4, 4) != "\r\n\r\n")
  149. {
  150. continue;
  151. }
  152. }
  153. else
  154. {
  155. return false;
  156. }
  157. return $this->doHandShake($headerBuffer);
  158. }
  159. return false;
  160. }
  161. /**
  162. * 握手
  163. * @param $headerBuffer
  164. * @return bool
  165. */
  166. function doHandShake($headerBuffer)
  167. {
  168. $header = Parser::parseHeader($headerBuffer);
  169. if (!isset($header['Sec-WebSocket-Accept']))
  170. {
  171. $this->disconnect();
  172. return false;
  173. }
  174. if ($header['Sec-WebSocket-Accept'] != base64_encode(pack('H*', sha1($this->key . self::GUID))))
  175. {
  176. $this->disconnect();
  177. return false;
  178. }
  179. $this->handshake = true;
  180. $this->header = $header;
  181. return true;
  182. }
  183. /**
  184. * Disconnect from server
  185. */
  186. public function disconnect()
  187. {
  188. $this->connected = false;
  189. $this->socket->close();
  190. }
  191. /**
  192. * 接收数据
  193. * @return bool | Swoole\Http\WebSocketFrame
  194. * @throws Swoole\Http\\Exception
  195. */
  196. function recv()
  197. {
  198. if (!$this->handshake)
  199. {
  200. trigger_error("not complete handshake.");
  201. return false;
  202. }
  203. while (true)
  204. {
  205. $data = $this->socket->recv();
  206. if (!$data)
  207. {
  208. return false;
  209. }
  210. $this->parser->push($data);
  211. $frame = $this->parser->pop($data);
  212. if ($frame)
  213. {
  214. return $frame->data;
  215. }
  216. }
  217. return false;
  218. }
  219. /**
  220. * send string data
  221. * @param $data
  222. * @param string $type
  223. * @param bool $masked
  224. * @throws \Exception
  225. * @return bool
  226. */
  227. public function send($data, $type = 'text', $masked = true)
  228. {
  229. if (empty($data))
  230. {
  231. throw new \Exception("data is empty");
  232. }
  233. if (!$this->handshake)
  234. {
  235. trigger_error("not complete handshake.");
  236. return false;
  237. }
  238. if ($this->haveSwooleEncoder)
  239. {
  240. switch($type)
  241. {
  242. case 'text':
  243. $_type = WEBSOCKET_OPCODE_TEXT;
  244. break;
  245. case 'binary':
  246. case 'bin':
  247. $_type = WEBSOCKET_OPCODE_BINARY;
  248. break;
  249. default:
  250. return false;
  251. }
  252. $_send = \swoole_websocket_server::pack($data, $_type);
  253. }
  254. else
  255. {
  256. $_send = $this->hybi10Encode($data, $type, $masked);
  257. }
  258. return $this->socket->send($_send);
  259. }
  260. /**
  261. * send json object
  262. * @param $data
  263. * @param bool $masked
  264. * @return bool
  265. */
  266. function sendJson($data, $masked = true)
  267. {
  268. return $this->send(json_encode($data, JSON_UNESCAPED_UNICODE).PACKAGE_EOF, 'text', $masked);
  269. }
  270. /**
  271. * Create header for websocket client
  272. * @return string
  273. */
  274. final protected function createHeader()
  275. {
  276. $host = $this->host;
  277. if ($host === '127.0.0.1' || $host === '0.0.0.0')
  278. {
  279. $host = 'localhost';
  280. }
  281. return "GET {$this->path} HTTP/1.1" . "\r\n" .
  282. "Origin: null" . "\r\n" .
  283. "Host: {$host}:{$this->port}" . "\r\n" .
  284. "Sec-WebSocket-Key: {$this->key}" . "\r\n" .
  285. "User-Agent: ".self::UserAgent."/" . self::VERSION . "\r\n" .
  286. "Upgrade: Websocket" . "\r\n" .
  287. "Connection: Upgrade" . "\r\n" .
  288. "Sec-WebSocket-Protocol: wamp" . "\r\n" .
  289. "Sec-WebSocket-Version: 13" . "\r\n" . "\r\n";
  290. }
  291. /**
  292. * Parse raw incoming data
  293. *
  294. * @param $header
  295. * @return array
  296. */
  297. final protected function parseIncomingRaw($header)
  298. {
  299. $retval = array();
  300. $content = "";
  301. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
  302. foreach ($fields as $field) {
  303. if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
  304. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function ($matches) {
  305. return strtoupper($matches[0]);
  306. }, strtolower(trim($match[1])));
  307. if (isset($retval[$match[1]])) {
  308. $retval[$match[1]] = array($retval[$match[1]], $match[2]);
  309. } else {
  310. $retval[$match[1]] = trim($match[2]);
  311. }
  312. } else if (preg_match('!HTTP/1\.\d (\d)* .!', $field)) {
  313. $retval["status"] = $field;
  314. } else {
  315. $content .= $field . "\r\n";
  316. }
  317. }
  318. $retval['content'] = $content;
  319. return $retval;
  320. }
  321. /**
  322. * Generate token
  323. *
  324. * @param int $length
  325. * @return string
  326. */
  327. private function generateToken($length)
  328. {
  329. $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
  330. $useChars = array();
  331. // select some random chars:
  332. for ($i = 0; $i < $length; $i++) {
  333. $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
  334. }
  335. // Add numbers
  336. array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
  337. shuffle($useChars);
  338. $randomString = trim(implode('', $useChars));
  339. $randomString = substr($randomString, 0, self::TOKEN_LENGHT);
  340. return base64_encode($randomString);
  341. }
  342. /**
  343. * Generate token
  344. *
  345. * @param int $length
  346. * @return string
  347. */
  348. public function generateAlphaNumToken($length)
  349. {
  350. $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
  351. srand((float)microtime() * 1000000);
  352. $token = '';
  353. do
  354. {
  355. shuffle($characters);
  356. $token .= $characters[mt_rand(0, (count($characters) - 1))];
  357. } while (strlen($token) < $length);
  358. return $token;
  359. }
  360. /**
  361. * @param $payload
  362. * @param string $type
  363. * @param bool $masked
  364. * @return bool|string
  365. */
  366. private function hybi10Encode($payload, $type = 'text', $masked = true)
  367. {
  368. $frameHead = array();
  369. $payloadLength = strlen($payload);
  370. switch ($type)
  371. {
  372. //文本内容
  373. case 'text':
  374. // first byte indicates FIN, Text-Frame (10000001):
  375. $frameHead[0] = 129;
  376. break;
  377. //二进制内容
  378. case 'binary':
  379. case 'bin':
  380. // first byte indicates FIN, Text-Frame (10000010):
  381. $frameHead[0] = 130;
  382. break;
  383. case 'close':
  384. // first byte indicates FIN, Close Frame(10001000):
  385. $frameHead[0] = 136;
  386. break;
  387. case 'ping':
  388. // first byte indicates FIN, Ping frame (10001001):
  389. $frameHead[0] = 137;
  390. break;
  391. case 'pong':
  392. // first byte indicates FIN, Pong frame (10001010):
  393. $frameHead[0] = 138;
  394. break;
  395. }
  396. // set mask and payload length (using 1, 3 or 9 bytes)
  397. if ($payloadLength > 65535)
  398. {
  399. $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
  400. $frameHead[1] = ($masked === true) ? 255 : 127;
  401. for ($i = 0; $i < 8; $i++)
  402. {
  403. $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
  404. }
  405. // most significant bit MUST be 0 (close connection if frame too big)
  406. if ($frameHead[2] > 127)
  407. {
  408. $this->socket->close();
  409. return false;
  410. }
  411. }
  412. elseif ($payloadLength > 125)
  413. {
  414. $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
  415. $frameHead[1] = ($masked === true) ? 254 : 126;
  416. $frameHead[2] = bindec($payloadLengthBin[0]);
  417. $frameHead[3] = bindec($payloadLengthBin[1]);
  418. }
  419. else
  420. {
  421. $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
  422. }
  423. // convert frame-head to string:
  424. foreach (array_keys($frameHead) as $i)
  425. {
  426. $frameHead[$i] = chr($frameHead[$i]);
  427. }
  428. // generate a random mask:
  429. $mask = array();
  430. if ($masked === true)
  431. {
  432. for ($i = 0; $i < 4; $i++)
  433. {
  434. $mask[$i] = chr(rand(0, 255));
  435. }
  436. $frameHead = array_merge($frameHead, $mask);
  437. }
  438. $frame = implode('', $frameHead);
  439. // append payload to frame:
  440. for ($i = 0; $i < $payloadLength; $i++)
  441. {
  442. $frame .= $masked ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
  443. }
  444. return $frame;
  445. }
  446. /**
  447. * @param $data
  448. * @return string
  449. * @throws \Exception
  450. */
  451. private function hybi10Decode($data)
  452. {
  453. if (empty($data))
  454. {
  455. throw new \Exception("data is empty");
  456. }
  457. $bytes = $data;
  458. $secondByte = sprintf('%08b', ord($bytes[1]));
  459. $masked = ($secondByte[0] == '1') ? true : false;
  460. $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
  461. //服务器不会设置mask
  462. if ($dataLength === 126)
  463. {
  464. $decodedData = substr($bytes, 4);
  465. }
  466. elseif ($dataLength === 127)
  467. {
  468. $decodedData = substr($bytes, 10);
  469. }
  470. else
  471. {
  472. $decodedData = substr($bytes, 2);
  473. }
  474. exit("len=".$dataLength."\n");
  475. return $decodedData;
  476. }
  477. }