WebsocketClient.Class.php 14 KB

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