Skip to content
This repository has been archived by the owner on Jul 9, 2019. It is now read-only.

Commit

Permalink
init commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
overtrue committed Jun 23, 2019
0 parents commit 21e6131
Show file tree
Hide file tree
Showing 17 changed files with 1,085 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = false

[*.{vue,js,scss}]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
11 changes: 11 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
* text=auto

/tests export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.scrutinizer.yml export-ignore
.travis.yml export-ignore
phpunit.php export-ignore
phpunit.xml.dist export-ignore
phpunit.xml export-ignore
.php_cs export-ignore
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.idea
*.DS_Store
/vendor
/coverage
sftp-config.json
composer.lock
.subsplit
.php_cs.cache
27 changes: 27 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
$header = <<<EOF
This file is part of the overtrue/websocket-client.
(c) overtrue <anzhengchao@gmail.com>
This source file is subject to the MIT license that is bundled.
EOF;

return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules(array(
'@Symfony' => true,
'header_comment' => array('header' => $header),
'array_syntax' => array('syntax' => 'short'),
'ordered_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'php_unit_construct' => true,
'php_unit_strict' => true,
))
->setFinder(
PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__)
)
;
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<h1 align="center"> websocket-client </h1>

<p align="center"> A PHP WebSocket client..</p>


## Installing

```shell
$ composer require overtrue/websocket-client -vvv
```

## Usage

TODO

## Contributing

You can contribute in one of three ways:

1. File bug reports using the [issue tracker](https://github.com/overtrue/websocket-client/issues).
2. Answer questions or fix bugs on the [issue tracker](https://github.com/overtrue/websocket-client/issues).
3. Contribute new features or update the wiki.

_The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable._

## License

MIT
19 changes: 19 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "overtrue/websocket",
"description": "A PHP implementation of WebSocket.",
"license": "MIT",
"authors": [
{
"name": "overtrue",
"email": "anzhengchao@gmail.com"
}
],
"require": {
"php": "^7.1.3"
},
"autoload": {
"psr-4": {
"Overtrue\\WebSocket\\": "src"
}
}
}
30 changes: 30 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/*
* This file is part of the overtrue/websocket-client.
*
* (c) overtrue <anzhengchao@gmail.com>
*
* This source file is subject to the MIT license that is bundled.
*/

include __DIR__.'/vendor/autoload.php';

//
//use WebSocket\Client;
//
//$client = new Client("ws://echo.websocket.org/");
//$client->send("Hello WebSocket.org!");
//
//echo $client->receive(); // Will output 'Hello WebSocket.org!'

//--------------------------------

use Overtrue\WebSocket\Client;

$socket = new Client('ws://echo.websocket.org/');

$socket->send('Hello WebSocket.org!');
$socket->send('Hello world!');

var_dump($socket->receive());
21 changes: 21 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
163 changes: 163 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
<?php

/*
* This file is part of the overtrue/websocket-client.
*
* (c) overtrue <anzhengchao@gmail.com>
*
* This source file is subject to the MIT license that is bundled.
*/

namespace Overtrue\WebSocket;

use Overtrue\WebSocket\Exceptions\ConnectionException;
use Overtrue\WebSocket\Exceptions\InvalidUriException;

/**
* Class Client.
*/
class Client extends WebSocket
{
/**
* @var string
*/
protected $uri;

/**
* Client constructor.
*
* @param string $uri
* @param array $options
*/
public function __construct(string $uri, array $options = [])
{
if (false === \strpos($uri, '://')) {
$uri = 'ws://'.$uri;
} elseif (0 !== \strpos($uri, 'ws://') && 0 !== \strpos($uri, 'wss://')) {
return new InvalidUriException(\sprintf('Given URI "%s" is invalid', $uri));
}

$this->uri = $uri;
$this->options = \array_merge($this->options, $options);
}

/**
* @param string $payload
* @param string $opcode
* @param bool $masked
*
* @throws \Overtrue\WebSocket\Exceptions\ConnectionException
*/
public function send(string $payload, string $opcode = 'text', bool $masked = true)
{
if (!$this->connected) {
$this->connect();
}

parent::send($payload, $opcode, $masked);
}

/**
* @param bool $try
*
* @return bool|string|null
*
* @throws \Overtrue\WebSocket\Exceptions\ConnectionException
* @throws \Overtrue\WebSocket\Exceptions\InvalidOpcodeException
*/
public function receive(bool $try = false)
{
if (!$this->connected) {
$this->connect();
}

return parent::receive($try);
}

/**
* @throws \Overtrue\WebSocket\Exceptions\ConnectionException
*/
public function connect()
{
$segments = \parse_url($this->uri);
$scheme = 'wss' === $segments['scheme'] ? 'ssl' : 'tcp';
$segments['port'] = $segments['port'] ?? ('wss' === $segments['scheme'] ? 443 : 80);
$url = \sprintf('%s://%s:%s', $scheme, $segments['host'], $segments['port']);

$this->socket = @\stream_socket_client($url, $errno, $errorMessage, $this->options['timeout'], \STREAM_CLIENT_CONNECT);

if (!$this->socket) {
throw new ConnectionException(\sprintf('Unable to connect to socket "%s": [%s]%s', $this->uri, $errno, $errorMessage));
}

stream_set_timeout($this->socket, $this->options['timeout']);

$this->performHandshake();

stream_set_blocking($this->socket, false);

$this->connected = true;
}

/**
* @throws \Overtrue\WebSocket\Exceptions\ConnectionException
*/
protected function performHandshake()
{
$key = base64_encode(\substr(md5(time().mt_rand(0, 100)), 0, 16));
$segments = array_merge([
'path' => '/',
'query' => '',
'query' => '',
'fragment' => '',
'user' => '',
'pass' => '',
], \parse_url($this->uri));

$segments['port'] = $segments['port'] ?? ('wss' === $segments['scheme'] ? 443 : 80);
$pathWithQuery = $segments['path'];

if (!empty($segments['query'])) {
$pathWithQuery .= '?'.$segments['query'];
}

if (!empty($segments['fragment'])) {
$pathWithQuery .= '#'.$segments['fragment'];
}

$headers = [
"GET {$pathWithQuery} HTTP/1.1",
"Host: {$segments['host']}:{$segments['port']}",
'User-Agent: websocket-client-php',
'Upgrade: websocket',
'Connection: Upgrade',
"Sec-WebSocket-Key: {$key}",
'Sec-WebSocket-Version: 13',
"\r\n",
];

if (!empty($this->options['origin'])) {
$headers[] = "Sec-WebSocket-Origin: {$this->options['origin']}";
}

if ($segments['user'] || $segments['pass']) {
$headers['Authorization'] = 'Basic '.base64_encode($segments['user'].':'.$segments['pass']);
}

if (isset($this->options['headers'])) {
$headers = array_merge($headers, $this->options['headers']);
}

@\fwrite($this->socket, \join("\r\n", $headers));

$response = \stream_socket_recvfrom($this->socket, 1024);

preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $response, $matches);

if ($matches) {
if (trim($matches[1]) !== base64_encode(pack('H*', sha1($key.self::KEY_SALT)))) {
throw new ConnectionException(\sprintf('Unable to upgrade to socket "%s"', $this->uri));
}
}
}
}
18 changes: 18 additions & 0 deletions src/Exceptions/BadRequestException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* This file is part of the overtrue/websocket-client.
*
* (c) overtrue <anzhengchao@gmail.com>
*
* This source file is subject to the MIT license that is bundled.
*/

namespace Overtrue\WebSocket\Exceptions;

/**
* Class BadRequestException.
*/
class BadRequestException extends Exception
{
}
15 changes: 15 additions & 0 deletions src/Exceptions/ConnectionException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

/*
* This file is part of the overtrue/websocket-client.
*
* (c) overtrue <anzhengchao@gmail.com>
*
* This source file is subject to the MIT license that is bundled.
*/

namespace Overtrue\WebSocket\Exceptions;

class ConnectionException extends Exception
{
}
18 changes: 18 additions & 0 deletions src/Exceptions/Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* This file is part of the overtrue/websocket-client.
*
* (c) overtrue <anzhengchao@gmail.com>
*
* This source file is subject to the MIT license that is bundled.
*/

namespace Overtrue\WebSocket\Exceptions;

/**
* Class Exception.
*/
class Exception extends \Exception
{
}
Loading

0 comments on commit 21e6131

Please sign in to comment.