Skip to content

Commit

Permalink
init prject
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 26, 2018
0 parents commit f70587c
Show file tree
Hide file tree
Showing 10 changed files with 789 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
root = true

# 对所有文件生效
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

# 对后缀名为 md 的文件生效
[*.md]
trim_trailing_whitespace = false

[*.php]
indent_size = 4
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.idea/
.phpintel/
!README.md
!.gitkeep
composer.lock
*.swp
*.log
*.pid
*.patch
.DS_Store
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2016 inhere

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# websocket utils

## install

```bash
composer require mylib/websocket-utils
```

## license

MIT
32 changes: 32 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "mylib/websocket-utils",
"type": "library",
"description": "some helper tool library of the php",
"keywords": ["library","tool","php"],
"homepage": "https://github.com/php-mylib/websocket-utils",
"license": "MIT",
"authors": [
{
"name": "inhere",
"email": "[email protected]",
"homepage": "http://www.yzone.net/"
}
],
"require": {
"php": ">=7.0.0",
"mylib/arr-utils": "~1.0",
"mylib/obj-utils": "~1.0",
"mylib/str-utils": "~1.0",
"mylib/sys-utils": "~1.0",
"mylib/php-utils": "~1.0"
},
"autoload": {
"psr-4": {
"MyLib\\WebSocket\\Client\\" : "src/"
}
},
"suggest": {
"inhere/php-validate": "Very lightweight data validate tool",
"inhere/console": "a lightweight php console application library."
}
}
24 changes: 24 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="test/boot.php"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Php Library Test Suite">
<directory>test</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
187 changes: 187 additions & 0 deletions src/Helper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php
/**
* Created by PhpStorm.
* User: Inhere
* Date: 2017/4/3 0003
* Time: 01:05
*/

namespace MyLib\WebSocket\Util;

/**
* Class WSHelper
* @package MyLib\WebSocket\Util
*/
class Helper
{
public static function encode()
{

}

/**
* @param string$s
* @return string
*/
public static function frame(string $s): string
{
$a = str_split($s, 125);
$prefix = WebSocketInterface::BINARY_TYPE_BLOB;

if (\count($a) === 1) {
return $prefix . \chr(\strlen($a[0])) . $a[0];
}

$ns = '';

foreach ($a as $o) {
$ns .= $prefix . \chr(\strlen($o)) . $o;
}

return $ns;
}

/**
* @param $buffer
* @return string
*/
public static function decode($buffer)
{
/*$len = $masks = $data =*/
$decoded = '';
$len = \ord($buffer[1]) & 127;

if ($len === 126) {
$masks = \substr($buffer, 4, 4);
$data = \substr($buffer, 8);
} else if ($len === 127) {
$masks = \substr($buffer, 10, 4);
$data = \substr($buffer, 14);
} else {
$masks = \substr($buffer, 2, 4);
$data = \substr($buffer, 6);
}

$dataLen = \strlen($data);
for ($index = 0; $index < $dataLen; $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
}

return $decoded;
}

/**
* @param string $payload
* @param string $type
* @param bool $masked
* @return bool|string
* @throws \Exception
*/
public static function hybi10Encode(string $payload, string $type = 'text', bool $masked = true)
{
$frameHead = array();
$payloadLength = \strlen($payload);

switch ($type) {
//文本内容
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;
//二进制内容
case 'binary':
case 'bin':
// first byte indicates FIN, Text-Frame (10000010):
$frameHead[0] = 130;
break;
case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;
case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;
case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}

// set mask and payload length (using 1, 3 or 9 bytes)
if ($payloadLength > 65535) {
$payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 255 : 127;

for ($i = 0; $i < 8; $i++) {
$frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
}

// most significant bit MUST be 0 (close connection if frame too big)
if ($frameHead[2] > 127) {
// todo `$this->close()`;
return false;
}
} elseif ($payloadLength > 125) {
$payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 254 : 126;
$frameHead[2] = bindec($payloadLengthBin[0]);
$frameHead[3] = bindec($payloadLengthBin[1]);
} else {
$frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
}

// convert frame-head to string:
foreach ($frameHead as $i => $v) {
$frameHead[$i] = \chr($frameHead[$i]);
}

// generate a random mask:
$mask = array();
if ($masked === true) {
for ($i = 0; $i < 4; $i++) {
$mask[$i] = \chr(random_int(0, 255));
}

$frameHead = array_merge($frameHead, $mask);
}

$frame = implode('', $frameHead);

// append payload to frame:
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= $masked ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}

return $frame;
}

/**
* @param string $data
* @return string
* @throws \InvalidArgumentException
*/
public static function hybi10Decode(string $data): string
{
if (!$data) {
throw new \InvalidArgumentException('data is empty');
}

$bytes = $data;
$secondByte = sprintf('%08b', \ord($bytes[1]));
$masked = '1' === $secondByte[0];
$dataLength = ($masked === true) ? \ord($bytes[1]) & 127 : \ord($bytes[1]);

//服务器不会设置mask
if ($dataLength === 126) {
$decodedData = \substr($bytes, 4);
} elseif ($dataLength === 127) {
$decodedData = \substr($bytes, 10);
} else {
$decodedData = \substr($bytes, 2);
}

return $decodedData;
}

}
Loading

0 comments on commit f70587c

Please sign in to comment.