Giter Site home page Giter Site logo

arthurkushman / php-wss Goto Github PK

View Code? Open in Web Editor NEW
206.0 17.0 31.0 209 KB

Web-socket server/client with multi-process and parse templates support on server and send/receive options on client

License: MIT License

PHP 100.00%
php websocket websockets processes routes websocket-server websocket-client multi-process

php-wss's Introduction

php-wss

Web-socket server/client with multi-process and parse templates support on server and send/receive options on client

Scrutinizer Code Quality Build Status Latest Stable Version Total Downloads License: MIT

Library comes with several main options

Server:

  • it`s a web-socket server for multiple connections with decoding/encoding for all events out of the box (with Dependency Injected MessageHandler)
  • it has GET uri parser, so you can easily use any templates
  • multiple process per user connections support, so you can fork processes to speed up performance deciding how many client-connections should be there
  • broadcasting message(s) to all clients
  • origin check
  • ssl server run

Client:

  • You have the ability to handshake (which is performed automatically) and send messages to server
  • Receive a response from the server
  • Initiate connection via proxy

How do I get set up?

Preferred way to install is with Composer.

perform command in shell

 composer require arthurkushman/php-wss

OR

just add

"require": {
  "arthurkushman/php-wss": ">=1.3"
}

to your projects composer.json.

Implement your WebSocket handler class - ex.:

<?php
use WSSC\Contracts\ConnectionContract;
use WSSC\Contracts\WebSocket;
use WSSC\Exceptions\WebSocketException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class ServerHandler extends WebSocket
{

    /*
     *  if You need to parse URI context like /messanger/chat/JKN324jn4213
     *  You can do so by placing URI parts into an array - $pathParams, when Socket will receive a connection
     *  this variable will be appropriately set to key => value pairs, ex.: ':context' => 'chat'
     *  Otherwise leave $pathParams as an empty array
     */

    public $pathParams = [':entity', ':context', ':token'];
    private $clients = [];

    private $log;

    /**
     * ServerHandler constructor.
     *
     * @throws \Exception
     */
    public function __construct()
    {
        // create a log channel
        $this->log = new Logger('ServerSocket');
        $this->log->pushHandler(new StreamHandler('./tests/tests.log'));
    }

    public function onOpen(ConnectionContract $conn)
    {
        $this->clients[$conn->getUniqueSocketId()] = $conn;
        $this->log->debug('Connection opend, total clients: ' . count($this->clients));
    }

    public function onMessage(ConnectionContract $recv, $msg)
    {
        $this->log->debug('Received message:  ' . $msg);
        $recv->send($msg);
    }

    public function onClose(ConnectionContract $conn)
    {
        unset($this->clients[$conn->getUniqueSocketId()]);
        $this->log->debug('close: ' . print_r($this->clients, 1));
        $conn->close();
    }

    /**
     * @param ConnectionContract $conn
     * @param WebSocketException $ex
     */
    public function onError(ConnectionContract $conn, WebSocketException $ex)
    {
        echo 'Error occured: ' . $ex->printStack();
    }

    /**
     * You may want to implement these methods to bring ping/pong events
     *
     * @param ConnectionContract $conn
     * @param string $msg
     */
    public function onPing(ConnectionContract $conn, $msg)
    {
        // TODO: Implement onPing() method.
    }

    /**
     * @param ConnectionContract $conn
     * @param $msg
     * @return mixed
     */
    public function onPong(ConnectionContract $conn, $msg)
    {
        // TODO: Implement onPong() method.
    }
}

To save clients with their unique ids - use getUniqueSocketId() which returns (type-casted to int) socketConnection resource id.

Then put code bellow to Your CLI/Console script and run

<?php
use WSSC\WebSocketServer;
use WSSCTEST\ServerHandler;
use WSSC\Components\ServerConfig;

$config = new ServerConfig();
$config->setClientsPerFork(2500);
$config->setStreamSelectTimeout(2 * 3600);

$webSocketServer = new WebSocketServer(new ServerHandler(), $config);
$webSocketServer->run();

How do I set WebSocket Client connection?

<?php
use WSSC\WebSocketClient;
use \WSSC\Components\ClientConfig;

$client = new WebSocketClient('ws://localhost:8000/notifications/messanger/yourtoken123', new ClientConfig());
$client->send('{"user_id" : 123}');
echo $client->receive();

That`s it, client is just sending any text content (message) to the Server.

Server reads all the messages and push them to Handler class, for further custom processing.

How to pass an optional timeout, headers, fragment size etc?

You can pass optional configuration to WebSocketClient's constructor e.g.:

<?php
use WSSC\WebSocketClient;
use WSSC\Components\ClientConfig;

$config = new ClientConfig();
$config->setFragmentSize(8096);
$config->setTimeout(15);
$config->setHeaders([
    'X-Custom-Header' => 'Foo Bar Baz',
]);

// if proxy settings is of need
$config->setProxy('127.0.0.1', '80');
$config->setProxyAuth('proxyUser', 'proxyPass');

$client = new WebSocketClient('ws://localhost:8000/notifications/messanger/yourtoken123', $config);

If it is of need to send ssl requests just set wss scheme to constructors url param of WebSocketClient - it will be passed and used as ssl automatically.

You can also set particular context options for stream_context_create to provide them to stream_socket_client, for instance:

$config = new ClientConfig();
$config->setContextOptions(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]);

or any other available options see - https://www.php.net/manual/en/context.php.

BroadCasting

You may wish to broadcast messages by simply calling broadCast method on Connection object in any method of your ServerHandler class:

$conn->broadCast('hey everybody...');

// or to send multiple messages with 2 sec delay between them
$conn->broadCastMany(['Hello', 'how are you today?', 'have a nice day'], 2);

Origin check

To let server check the Origin header with n hosts provided:

$config = new ServerConfig();
$config->setOrigins(["example.com", "otherexample.com"]);
$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();

Server will automatically check those hosts proceeding to listen for other connections even if some failed to pass check.

SSL Server run options

use WSSC\Components\ServerConfig;
use WSSC\WebSocketServer;

$config = new ServerConfig();
$config->setIsSsl(true)->setAllowSelfSigned(true)
    ->setCryptoType(STREAM_CRYPTO_METHOD_SSLv23_SERVER)
    ->setLocalCert("./tests/certs/cert.pem")->setLocalPk("./tests/certs/key.pem")
    ->setPort(8888);

$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();

Avoid high CPU usage

use WSSC\WebSocketServer;
use WSSCTEST\ServerHandler;
use WSSC\Components\ServerConfig;

$config = new ServerConfig();

// Set the read socket iteration delay in miliseconds
$config->setLoopingDelay(1);

$webSocketServer = new WebSocketServer(new ServerHandler(), $config);
$webSocketServer->run();

How to test

To run the Server - execute from the root of a project:

phpunit --bootstrap ./tests/_bootstrap.php ./tests/WebSocketServerTest.php

To run the Client - execute in another console:

phpunit --bootstrap ./tests/_bootstrap.php ./tests/WebSocketClientTest.php

PHP7 support since version 1.3 - with types, returns and better function implementations.

Benchmarks:

iter benchmark subject set revs mem_peak time_avg comp_z_value comp_deviation
0 MaxConnectionsBench benchConnect 10000 1,547,496b 4.831μs +1.41σ +6.35%
1 MaxConnectionsBench benchConnect 10000 1,547,496b 4.372μs -0.83σ -3.76%
2 MaxConnectionsBench benchConnect 10000 1,547,496b 4.425μs -0.57σ -2.59%
benchmark subject revs its mem_peak mode rstdev
MaxConnectionsBench benchConnect 10000 3 1.547mb 4.427μs ±4.51%

As you may have been noticed, average time to send msg is 4.427μs which is roughly rounded to 4 microseconds within 10 000 have been sent 3 times in a row.

PS U'll see the processes increase named "php-wss" as CPP (Connections Per-Process) will grow and decrease while stack will lessen. For instance, if set 100 CPP and there are 128 connections - You will be able to see 2 "php-wss" processes with for ex.: ps aux | grep php-wss

Used by:

alt Avito logo

Supporters gratitude:

JetBrains logo

php-wss's People

Contributors

arthurkushman avatar eusonlito avatar kekalainen avatar mnashmi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-wss's Issues

Push notifications to client

How to push notifications from the server to the client without the client sends a message to the server first?

At a given point something happens on the server and the server needs to push the notification to the client?

Where can I put logic that check for updates in the database?

It doesn't seem to be possible.. As I see it the server can only reply on a messages from the client...?

Problems with composer require arthurkushman/wss

If i run
composer require arthurkushman/wss

i've got:

santa@vyvoj:~/tmp/ws$ composer require arthurkushman/wss


  [InvalidArgumentException]
  Could not find package arthurkushman/wss at any version for your minimum-st
  ability (stable). Check the package spelling or your minimum-stability


require [--dev] [--prefer-source] [--prefer-dist] [--no-plugins] [--no-progress] [--no-update] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] [<packages>]...

WscMain return type : void not possible for PHP 7.0

Hey there,

may it be possible to remove the return type : void in the WscMain.php for all the functions? This will only work with PHP 7.2 but PHP 7.0 will throw errors because this return type is not supported in this version.

Thanks for your feedback 👍

stream_socket_accept(): Accept failed: Operation timed out

There was 1 error:

1) WSSCTEST\WebSocketServerTest::is_server_running
stream_socket_accept(): Accept failed: Operation timed out

/Users/mac/www/php-wss/src/WebSocketServer.php:202
/Users/mac/www/php-wss/src/WebSocketServer.php:184
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:138
/Users/mac/www/php-wss/src/WebSocketServer.php:167
/Users/mac/www/php-wss/src/WebSocketServer.php:141
/Users/mac/www/php-wss/src/WebSocketServer.php:119
/Users/mac/www/php-wss/tests/WebSocketServerTest.php:25

Get $this->socketConnection on Connection instance

It would be preferred if there was a simple getter to get the private $this->socketConnection in Connection class

Then its possible to do some comparing in the ServerHandler methods

public function get()
{
    return $this->socketConnection;
}

Incorrectly closed connections

Hello,

Connection object incorrectly closes connection. There is missing reply to client after receiving event close (with opcode 8 - DECODE_CLOSE). Result is exception fired in client (for example JavaScript console) after closing websocket and incomplete closed sockets at server (visible in netstat with flag CLOSE_WAIT):

s = new WebSocket("ws://nic.ehs.sk:8081/websocket/");
s.close();
Connection was interrupted while page is loading..

Solution is change Connection->close() method like this:

    public function close() : void
    {
        if (is_resource($this->socketConnection)) {
            // reply to close message
            fwrite($this->socketConnection, $this->encode('', self::EVENT_TYPE_CLOSE));
            fclose($this->socketConnection);
        }
    }

I'm new in Git/GutHub, and don't know to push patch to your project directly.

With regards
Michal

fwrite(): send of 2 bytes failed with errno=32 Broken pipe

Often I get this error

fwrite(): send of 2 bytes failed with errno=32 Broken pipe /var/www/.../php/class/third-party/php-wss/Components/Connection.php(32)
#0 [internal function]: {closure}(8, 'fwrite(): send ...', '/var/www/...', 32, Array)
#1 /var/www/.../php/class/third-party/php-wss/Components/Connection.php(32): fwrite(Resource id #27, '\x88\x00')
#2 /var/www/.../php/class/Websocket.php(102): WSSC\Components\Connection->close()
#3 /var/www/.../php/class/third-party/php-wss/WebSocketServer.php(195): ServerHandler->onClose(Object(WSSC\Components\Connection))
#4 /var/www/.../php/class/third-party/php-wss/WebSocketServer.php(145): WSSC\WebSocketServer->messagesWorker(Array)
#5 /var/www/.../php/class/third-party/php-wss/WebSocketServer.php(100): WSSC\WebSocketServer->looping(Resource id #25)
#6 /var/www/.../php/class/third-party/php-wss/WebSocketServer.php(75): WSSC\WebSocketServer->eventLoop(Resource id #25)
#7 /var/www/.../public/websocket/index.php(31): WSSC\WebSocketServer->run()
#8 {main}

Close connection from server-side

If you close the connection from the ServerHandler you get an error

	public function onMessage(ConnectionContract $conn, $msg){
		$socket_id 		= $conn->getUniqueSocketId();
		$json 			= json_decode($msg, true);
		
		if(empty($json['sid'])){
			$conn->close();
		}
	}

error

fwrite(): supplied resource is not a valid stream resource /var/www/.../php/class/third-party/php-wss/Components/Connection.php(41)
#0 [internal function]: {closure}(2, 'fwrite(): suppl...', '/var/www/...', 41, Array)
#1 /var/www/.../php/class/third-party/php-wss/Components/Connection.php(41): fwrite(Resource id #31, '\x81={"sid":"k0krg...')
#2 /var/www/.../php/class/Websocket.php(82): WSSC\Components\Connection->send('{"sid":"k0krggq...')
#3 /var/www/.../php/class/third-party/php-wss/WebSocketServer.php(215): ServerHandler->onMessage(Object(WSSC\Components\Connection), '{"sid":"k0krggq...')

die on timeout

Its still there?

if (!stream_select($readSocks, $write, $except, $this->config->getStreamSelectTimeout())) {
                die('something went wrong while selecting');
            }

multiple send is not working correctly.

    $config = new ClientConfig();
    $config->setTimeout(10);
    $config->setFragmentSize(406400);
    $client = new WebSocketClient( getenv('WEBSOCKET_ENDPOINT') , $config );
    $client->send("THISISDATA1");
    $client->send("THISISDATA2");
    $client->send("THISISDATA3");
    $client->send("THISISDATA4");

3rd message, 4th message does not send to server.

Do you have any idea?

Multiple new Connection initiates

I can see you have more than one new Connection

For better performance I would recommend only doing it once but then store all connections in an array like you store all clients as a property in the class

167            $this->handler->onOpen(new Connection($newClient));
...
189            $this->cureentConn = new Connection($sock);

Connection->socketConnection changes

Hello,
in WebSocketServer you use still the same object Connection and only change his $socketConnection property. This is wrong.
In implementation example (ServerHandler) after two clients connects, property ServerHandler::clients will have two identical elements (because objects in PHP are passed by reference).

Better solution is to remove Connection::getConnection method, create constructor of Connection:
public function __construct($sockConn) { $this->socketConnection = $sockConn; }

and in WebSocketServer every time to create new object Connection:
new Connection($newClient);
instead of
$this->connImpl->getConnection($newClient)

With regards
Michal

clients getting more resource ids

System: Linux, PHP 7.2

Steps to reproduce:

What should happen:

$clients should contain nothing after all connections are closed.

What actually happened:

$clients contains some WSSC\Components\Connection Objects and some with more than one resource.

More info:

The onClose function doesn't find $conn in $clients as more resources were added in the mean time (except the first connection).
Thus the connections can't be unset and stay in $clients.

Websocket limits Timeout and Clients per Fork

Is there any way to set Timeout forever and infinite Clients per Fork? Or should I just put a big enough number? Because I'm using it to replace the websocket of an exchange.

PS: I loved your code, put a Sponsor that accepts bitcoin :)

Bug: unsaved large frame payload and closed connection (on server)

Fist off, THANK YOU for making this code available. Saved me a ton of time making wss work between js and php. Trying to get wss working from js without a proxy is not a simple thing.

I think you have a bug in WssMain.php in decode(). You correctly state:

"We have to check for large frames here. socket_recv cuts at 1024 bytes so if websocket-frame is > 1024 bytes we have to wait until whole data is transferd."

However, the data from the current packet is not saved anywhere so that it can be added to the next one when it is received.

WscMain->write(): fflush($handle) missed

First way to resolve:

    protected function write(string $data) : void
    {
        $written = fwrite($this->socket, $data);
        fflush($this->socket);
        if ($written < strlen($data)) {
            throw new ConnectionException(
                "Could only write $written out of " . strlen($data) . " bytes."
            );
        }
    }

Second way to resolve:

    public function flush() {
        return fflush($this->socket);
    }

Proxy Connection Problem

Hi,

in File WscMain and method proxy() i can see, that you send a CONNECT Request to the Proxy Server itselfs. Shouldn't it be the target Host (Line 135)?

For my undeerstanding otherwise the Messages are not sendet to the Target Host.

Regards

Getting error on setScheme() method

Hello

I'm trying to connect but 'im getting the following error:

Type: TypeError
Message: Return value of WSSC\Components\ClientConfig::setScheme() must be an instance of WSSC\Components\void, none returned
Filename: /var/www/vendor/arthurkushman/php-wss/src/Components/ClientConfig.php
Line Number: 102

My code is only:

    $config = new ClientConfig();
    $config->setContextOptions([
      'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
      ]
    ]);
    $client = new WebSocketClient('wss://127.0.0.1:2021', $config);

Do you have idea what I'm doing wrong? I tried to solve this but without success.

SSL Support

Hello, I want to ask if is possible to configure server with SSL certs. Or i need to hide it behind server.
Thanks.

Error codes

It must be simpler to identify errors.. Right now it is a bit complicated to handle errors

eg.
Socket timeout is not a fatal error so you need to know when this error is thrown so the application/script can be restarted

It would also be good practice to merge all exceptions to one error class and instead use error codes with a string like SOCKET_SELECTION_TIMEOUT.. It much easier to manage your error handling instead of long generic strings like something went wrong bla bla bla

It is also much more complicated to catch many different exceptions instead of just one. Then you can just fetch the error code or the error identifier like SOCKET_SELECTION_TIMEOUT and you know what went wrong and then you know what to do to solve the problem

while ($client->isConnected()) fail

test.wss.php:

use WSSC\WebSocketClient;
$client = new WebSocketClient('wss://....');
$client->setTimeout(15);
print $client->isConnected() ? 'yes' : 'no';
$ php test.wss.php
no

The $client->connect method protected and calls on send or receive only. I can't use it like this:

use WSSC\WebSocketClient;
$client = new WebSocketClient('wss://....');
$client->setTimeout(15);
while ($client->isConnected())
{
    // do something
}

Proxy problem

hello, i have problem when i used proxy connection. can you help me?

`error_reporting(E_ALL);
ini_set('display_errors', '1');

require DIR . '/vendor/autoload.php';
use WSSC\WebSocketClient;
use \WSSC\Components\ClientConfig;

$config = new ClientConfig();

$config->setProxy('24.24.25.25', '8085');
$config->setProxyAuth('MyUserName', 'MyPass');
$config->setContextOptions(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]);

$client = new WebSocketClient('ws://echo.websocket.org', $config);
$client->send("Hello");
echo $client->receive();`

Error Code : Fatal error: Uncaught WSSC\Exceptions\ConnectionException: Failed to connect to the host via proxy in /var/www/html/wbSystem/vendor/arthurkushman/php-wss/src/Components/WscMain.php:151 Stack trace: #0 /var/www/html/wbSystem/vendor/arthurkushman/php-wss/src/Components/WscMain.php(65): WSSC\Components\WscMain->proxy() #1 /var/www/html/wbSystem/vendor/arthurkushman/php-wss/src/WebSocketClient.php(26): WSSC\Components\WscMain->connect() #2 /var/www/html/wbSystem/index.php(16): WSSC\WebSocketClient->__construct('ws://echo.webso...', Object(WSSC\Components\ClientConfig)) #3 {main} thrown in /var/www/html/wbSystem/vendor/arthurkushman/php-wss/src/Components/WscMain.php on line 151

$this->clients all contain the last opened connection in each Connection instance

I need to store data on each client like session id etc

In the onMessage method I have this line $key = array_search($recv, $this->clients); but it always returns 1 ??

Even when there are multiply connected clients.. When a client sends a message to the server 1 is returned?

All clients are storing their data on client with key 1

class ServerHandler extends WebSocket {
    public $pathParams = [':entity', ':context', ':token'];
    private $clients        = [];
    private $client_data    = [];

    public function onOpen(ConnectionContract $conn){
        end($this->clients);
        $key = key($this->clients) + 1;
        
        $this->clients[$key] = $conn;
        echo 'Connection opend, total clients: ' . count($this->clients) . '('.$key.')' . PHP_EOL;
    }

    public function onMessage(ConnectionContract $recv, $msg){
        $key = array_search($recv, $this->clients);
        
        echo 'Received message ('.$key.'):  ' . $msg . PHP_EOL;
        
        $json = json_decode($msg, true);
        
        if(isset($json['sid'])){
            $this->client_data[$key]['sid'] = $json['sid'];
        }
        
        $recv->send($msg);
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.