GithubHelp home page GithubHelp logo

varspool / wrench Goto Github PK

View Code? Open in Web Editor NEW
595.0 36.0 209.0 1.06 MB

A simple PHP WebSocket implementation for PHP 7.1

License: Do What The F*ck You Want To Public License

PHP 100.00%
php wrench websockets

wrench's Introduction

Wrench

Simple WebSocket Client/Server for PHP

A simple websocket server and client package for PHP 7.1.

Installation

The library is PSR-4 compatible, with a vendor name of Wrench. It's available on Composer as wrench/wrench, so you can:

composer require wrench/wrench ~3.0

Usage

This creates a server on 127.0.0.1:8000 with one Application that listens for WebSocket requests to ws://localhost:8000/echo and ws://localhost:8000/chat:

Server

/**
 * An example application, that just echoes the received data back to the connection that sent it
 */
$app = new class implements \Wrench\Application\DataHandlerInterface
{
    public function onData(string $data, \Wrench\Connection $connection): void
    {
        $connection->send($data);
    }
};

// A websocket server, listening on port 8000
$server = new \Wrench\BasicServer('ws://localhost:8000', array(
    'allowed_origins' => array(
        'mysite.com',
        'mysite.dev.localdomain'
    )
));

$server->registerApplication('echo', $app);
$server->registerApplication('chat', new \My\ChatApplication());
$server->setLogger($monolog); // PSR3
$server->run();

Client

/**
 * A client side example, that sends a string and will receive the data back to the connection that sent it
 */
$client = new Client('ws://localhost:8000, http://localhost:8000);
$client->connect();
$client->sendData('hello');
$response = $client->receive()[0]->getPayload();
$client->disconnect();

Releases and Changelog

See the CHANGELOG for detailed information about changes between releases.

PHP5 Support

The latest major release dropped support for PHP versions prior to 7.1. If you need support for older versions of PHP, see the 2.0 branch. The latest 2.0 branch release is 2.0.8. You can install it with:

composer require wrench/wrench ~2.0

Developing

  • Run ./vendor/bin/phpcs and fix any errors that you come across
  • Run ./vendor/bin/phpunit --exclude-group large,medium for a fast test between changes

See Also

  • Ratchet an excellent Websocket layer for React.

wrench's People

Contributors

alarmfifa avatar bboer avatar daspors avatar dobrakmato avatar dominics avatar emadruida avatar evolve32 avatar feifengxlq avatar guweigang avatar huanga avatar jakubkulhan avatar jfcherng avatar joy2fun avatar mattexx avatar mazhack avatar mfairchild365 avatar mgiustiniani avatar nekudo avatar nexen2 avatar nicokaiser avatar positronium avatar rupert-rr avatar scrutinizer-auto-fixer avatar vincentdieltiens avatar zanechua 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wrench's Issues

Socket is not Connected while refresh

Hello !
While reloading a page with VarpoolWebSocket on Symfony 2 the Socket fails.
1- It disconnect properly the client
2- It Connected properly
3- The Hadshake is successful
4- When sending a message with send() function I've this error :
warning: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\SocketException' with message 'Socket is not connected' in /opt/lampp/htdocs/Korum/vendor/wrench/lib/Wrench/Socket/Socket.php:248

My wrench and my WebsocketsocketBundle are up to date both.

Dead Repo?

There's been no commits for a year, and no substantial ones for two. The standards supported by your original work (hixie-75, 76) are no longer supported by browsers. Meanwhile, other branches in the network have implemented hybi-10, 13, 17 support and extensive improvements (streams instead of sockets, bringing ssl support for one).

Just a friendly reminder that you can transfer ownership of the repo, and this will stop those 48 forks coming back to you with upstream requests. So, if you don't want to deal with the pain of pull requests and issues being filed, you can make it somebody else's problem from the 'admin' section (just ping someone in this issue to let them know before you transfer).

You can even keep your own repo. It's just that, as it is, somebody wanting to use the code has to wade through a forest of better forks to find the best one.

Documentation

This is a very very good library. But Documentation is almost missing.
For example is not documentated the ClientSocket, another excellent component.

fail to run the example!!! php -q server_ssl.php

Dear all:
When I run the example(server_ssl.php) in Wrench project
I got
Warning: require(/home/demo/Wrench-master/examples/../../vendor/autoload.php)

Fatal error: require(): Failed opening required '/home/demo/Wrench-master/examples/../../vendor/autoload.php' (include_path='.:/opt/php/lib/php') in /home/demo/Wrench-master/examples/server_ssl.php on line 16

anybody know why......???? or where is the autoload.php
thanks a lot

InvalidArgumentException does not exist

PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid request line' in /var/www/wrench/lib/Wrench/Protocol/Protocol.php:690
Stack trace:
#0 /var/www/wrench/lib/Wrench/Protocol/Protocol.php(441): Wrench\Protocol\Protocol->getRequestHeaders('<policy-file-re...')
#1 /var/www/wrench/lib/Wrench/Connection.php(199): Wrench\Protocol\Protocol->validateRequestHandshake('<policy-file-re...')
#2 /var/www/wrench/lib/Wrench/Connection.php(182): Wrench\Connection->handshake('<policy-file-re...')
#3 /var/www/wrench/lib/Wrench/Connection.php(397): Wrench\Connection->onData('<policy-file-re...')
#4 /var/www/wrench/lib/Wrench/ConnectionManager.php(245): Wrench\Connection->process()
#5 /var/www/wrench/lib/Wrench/ConnectionManager.php(172): Wrench\ConnectionManager->processClientSocket(Resource id #29)
#6 /var/www/wrench/lib/Wrench/Server.php(200): Wrench\ConnectionManager->selectAndProcess()
#7 /var/www/wrench/examples/server.php(48): Wrench\Server->run()
#8 {main}

thrown in /var/www/wrench/lib/Wrench/Protocol/Protocol.php on line 690

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid request line' in /var/www/wrench/lib/Wrench/Protocol/Protocol.php:690
Stack trace:
#0 /var/www/wrench/lib/Wrench/Protocol/Protocol.php(441): Wrench\Protocol\Protocol->getRequestHeaders('<policy-file-re...')
#1 /var/www/wrench/lib/Wrench/Connection.php(199): Wrench\Protocol\Protocol->validateRequestHandshake('<policy-file-re...')
#2 /var/www/wrench/lib/Wrench/Connection.php(182): Wrench\Connection->handshake('<policy-file-re...')
#3 /var/www/wrench/lib/Wrench/Connection.php(397): Wrench\Connection->onData('<policy-file-re...')
#4 /var/www/wrench/lib/Wrench/ConnectionManager.php(245): Wrench\Connection->process()
#5 /var/www/wrench/lib/Wrench/ConnectionManager.php(172): Wrench\ConnectionManager->processClientSocket(Resource id #29)
#6 /var/www/wrench/lib/Wrench/Server.php(200): Wrench\ConnectionManager->selectAndProcess()
#7 /var/www/wrench/examples/server.php(48): Wrench\Server->run()
#8 {main}

thrown in /var/www/wrench/lib/Wrench/Protocol/Protocol.php on line 690

Large message

The server hangs when transferring a large message(more than 1391 bytes)
PHP 5.3.3

Connection->configureClientId() makes bad use of gmp_init when the gmp extension is loaded

The Connection->configureClientId() method generates a hash of various variables for use as the id for a connection.
If the gmp module is available, it uses it to create a more compact string of the hash.
However, it tries to do this by initialising a GMP object with the raw binary representation of the hash (as returned by the native hash function). It would seem (this is certainly the case for me) that the gmp_init function cannot interpret the raw binary string as a number, so always interprets it as 0, leading to client id clashes.
Altering it from:

if (extension_loaded('gmp')) {
    $hash = hash($algo, $message, true);
    $hash = gmp_strval(gmp_init($hash, 16), 62);
}

to:

if (extension_loaded('gmp')) {
    $hash = hash($algo, $message);
    $hash = gmp_strval(gmp_init('0x'.$hash, 16), 62);
}

solves this for me.

onData not triggered

Using the basic EchoApplication:

$server->registerApplication('main', new \Wrench\Application\EchoApplication());

And some javascript/jQuery:

var connection = new WebSocket('wss://'+window.location.hostname+':7766/main');

connection.onmessage = function(e) {
  console.log('Server: ' + e.data);
}

$('#frm_send').submit(function(e) {
  connection.send($('#ws_text').val());
});

and html:

<form id="frm_send">
<input type="text" placeholder="send" id="ws_text"><input type="submit" value="send" id="ws_send" />
</form>

I do not receive the first data I send. when sending again, I receive what I sent the first time. Sending again I receive what I sent the second time and so on...

This seams like a bug where the onData function is not triggered at the right time or something.
I also see from the log that "Handling payload" is not triggering until the second time I send something, with what I sent the first time as input.

not completed exception handling can cause total crash

Application, handled websockets is supposed to be stable even in case of some problems on client side. Huge using exceptions without cath-try handling cause crashing.

For (first look) example Connection.__construct calls configureClientInformation with potential exception without try-catch. If new client connects, and invoke exception , all application crashes and all actually connected innocent clients have problem.

I have long-running PHP workers with monitoring possiblity through web sockets.
Newest version (2.0) of php-websockets (protocol 13) cannot be used without big risk or big rework.

How to correctly handle exceptions ?

PHP Fatal error: Class 'Wrench\\Socket\\ConnectionException' not found in /var/www/vendor/wrench/wrench/lib/Wrench/Socket/ClientSocket.php on line 61

I have a Phalcon app, and in one of my controllers, I need to connect to a WebSocket. However, when the connection fails, it gives a fatal error. Here are the relevant codes that lead up to that:

<?php
require __DIR__ . '/../../vendor/autoload.php';  // This is correct path to autoload through composer
use \Wrench\Client;

class ScoreboardController extends \Phalcon\Mvc\Controller {
    public function addAction() {
        $data_array = array("lorem" => "ipsum");
        try {
            $client = new Client('ws://localhost:8080/sbsync', 'http://localhost/');
            $client->connect();
            $client->sendData(json_encode($data_array));
        } catch (\Wrench\Exception\ConnectionException $e) {
            // Fails before reaching here, Class not found for \Wrench\Exception\ConnectionException
        }
    }
}

The error in apache log was: PHP Fatal error: Class 'Wrench\Socket\ConnectionException' not found in /var/www/vendor/wrench/wrench/lib/Wrench/Socket/ClientSocket.php on line 61

To fix this, I looked at that line, and modified it to include full namespace path (see following pull request).

ssl only: Error reading data from socket: Not connected

Chrome gives this error:
WebSocket connection to 'wss://server.somewhere:8000/echo' failed: WebSocket opening handshake was canceled

I get this error when testing server_ssl.php in cli:

root@m1048:/var/www/html/Wrench-master/examples# php -q server_ssl.php
info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 80.xxx.xxx.xxx:61207 (38bcbf66a45efe6f76292087dacb1b3fdbb35262dcce1d98c5473f0d4ba62794e0126f634cc264c519727021553be8b420fcb795f3f53eb6aa82cc7d7725a7c2): Connected
notice: Wrench\ConnectionManager: Client connection closed: exception 'Wrench\Exception\CloseException' with message 'Error reading data from socket: Not connected' in /var/www/html/Wrench-master/lib/Wrench/Connection.php:396
Stack trace:
#0 /var/www/html/Wrench-master/lib/Wrench/ConnectionManager.php(243): Wrench\Connection->process()
#1 /var/www/html/Wrench-master/lib/Wrench/ConnectionManager.php(168): Wrench\ConnectionManager->processClientSocket(Resource id #32)
#2 /var/www/html/Wrench-master/lib/Wrench/Server.php(198): Wrench\ConnectionManager->selectAndProcess()
#3 /var/www/html/Wrench-master/examples/server_ssl.php(54): Wrench\Server->run()
#4 {main}

warning: Wrench\ConnectionManager: Wrench\Connection: 80.xxx.xxx.xxx:61207 (38bcbf66a45efe6f76292087dacb1b3fdbb35262dcce1d98c5473f0d4ba62794e0126f634cc264c519727021553be8b420fcb795f3f53eb6aa82cc7d7725a7c2): Unable to send close message

This does not happen in normal plain "server.php" test, only in ssl.

Errors when WebSocket disconnects

I get the following errors when WebSocket disconnects

err: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\CloseException' with message 'Error reading data from socket: Unknown error' in ../test/wrench/lib/Wrench/Connection.php:399
Stack trace:
#0 ../test/wrench/lib/Wrench/ConnectionManager.php(232): Wrench\Connection->process()
#1 ../test/wrench/lib/Wrench/ConnectionManager.php(163): Wrench\ConnectionManager->processClientSocket(Resource id #20)
#2 ../test/wrench/lib/Wrench/Server.php(187): Wrench\ConnectionManager->selectAndProcess()
#3 ../test/wrench/examples/server.php(48): Wrench\Server->run()
#4 {main}

PHP Notice: Undefined variable: e in ../test/wrench/lib/Wrench/Connection.php on line 418

Notice: Undefined variable: e in ../test/wrench/lib/Wrench/Connection.php on line 418

Exceptions Galore

Hi,

I've moved from php-websockets to Wrench today, but I am in a sea of exceptions and errors now. I though you might like some feedback. Overall I love the concept of what I see and I look forward to using it in our web app to replace the ajax polling we are currently using.

By contract, php-websockets had none of these problems. I attempted to upgrade because we could never get WSS:// working with php-websockets.

We're developing on MAC, and testing with Safari 5.1.7, Chrome 20.0.1132.57 and FireFox 14.0.1. Difference browsers give us different errors.

Firstly, the we found when we start the server as below, it failed as it resolved localhost to ip6 ::1 hence ::1:8000 failed the host/port parsing.

server = new \Wrench\Server('ws://localhost:8000/', array(

We tested the connection in the JS console for each browser with the following code:

var ws = new WebSocket("ws://127.0.0.1:8000/echo");

Here are the results for each browser:

FireFox:

php wsserver.php
info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:60868 (380b0ff3ab4faecd6484fd92df6d998eedbe93aa279d34a244b3b4beba25a70dc1c1391cb3ec1636ccf32a98e5d335b65235e85da086182f4108e83701ceed6a): Connected
err: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\BadRequestException' with message 'Invalid connection header' in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Protocol/Protocol.php:452
Stack trace:
#0 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(206): Wrench\Protocol\Protocol->validateRequestHandshake('GET /echo HTTP/...')
#1 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(189): Wrench\Connection->handshake('GET /echo HTTP/...')
#2 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(402): Wrench\Connection->onData('GET /echo HTTP/...')
#3 /Users/lyndoch/dev/TokCam/php/lib/Wrench/ConnectionManager.php(232): Wrench\Connection->process()
#4 /Users/lyndoch/dev/TokCam/php/lib/Wrench/ConnectionManager.php(163): Wrench\ConnectionManager->processClientSocket(Resource id #20)
#5 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Server.php(187): Wrench\ConnectionManager->selectAndProcess()
#6 /Users/lyndoch/dev/TokCam/php/wsserver.php(48): Wrench\Server->run()
#7 {main}

PHP Notice: Undefined variable: e in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 415

Notice: Undefined variable: e in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 415

Chrome:

php wsserver.php
info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:60873 (6655c186e8eaa74e24618d140969f1c75de915da9aa81d53a6bde44c596948a481a26ff7fd0aa0d8ef9cd921805536fb7335e9ee7799ae2b976c0d1a4ad1e1e1): Connected
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:60873 (6655c186e8eaa74e24618d140969f1c75de915da9aa81d53a6bde44c596948a481a26ff7fd0aa0d8ef9cd921805536fb7335e9ee7799ae2b976c0d1a4ad1e1e1): Handshake successful: 127.0.0.1:60873 (6655c186e8eaa74e24618d140969f1c75de915da9aa81d53a6bde44c596948a481a26ff7fd0aa0d8ef9cd921805536fb7335e9ee7799ae2b976c0d1a4ad1e1e1) connected to /echo
PHP Fatal error: Call to undefined method Wrench\Application\EchoApplication::onConnect() in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 243

Fatal error: Call to undefined method Wrench\Application\EchoApplication::onConnect() in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 243

Safari:

php wsserver.php
info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:60879 (4955168f01e40bd1a0a23bde1c2a20aa9bfc7f34d83f9fffcfcf6cfc3820c5908bd89bfbfa082710d4a63d32fa1fe4c79cb04e3ffb94d33752102a11fc9c5f4a): Connected
err: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\BadRequestException' with message 'Invalid upgrade header' in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Protocol/Protocol.php:446
Stack trace:
#0 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(206): Wrench\Protocol\Protocol->validateRequestHandshake('GET /echo HTTP/...')
#1 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(189): Wrench\Connection->handshake('GET /echo HTTP/...')
#2 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php(402): Wrench\Connection->onData('GET /echo HTTP/...')
#3 /Users/lyndoch/dev/TokCam/php/lib/Wrench/ConnectionManager.php(232): Wrench\Connection->process()
#4 /Users/lyndoch/dev/TokCam/php/lib/Wrench/ConnectionManager.php(163): Wrench\ConnectionManager->processClientSocket(Resource id #20)
#5 /Users/lyndoch/dev/TokCam/php/lib/Wrench/Server.php(187): Wrench\ConnectionManager->selectAndProcess()
#6 /Users/lyndoch/dev/TokCam/php/wsserver.php(48): Wrench\Server->run()
#7 {main}

PHP Notice: Undefined variable: e in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 415

Notice: Undefined variable: e in /Users/lyndoch/dev/TokCam/php/lib/Wrench/Connection.php on line 415

Regards,
Gary.

Chrome 14.0.835 don't work

Hi. Thanks for your lib! But i have Chrome 14.0.835 and it sends some headers that your server doesn't support i think... For example there is no Origin header but Sec-Websocket-Origin and there is no Sec-WebSocket-Key1 and Sec-WebSocket-Key2, only Sec-WebSocket-Key... Will you update your server to match the latest Websocket drafts ? Thanks!

Warning: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\BadRequestException' with message 'Invalid application'

Hello,
I downloaded 2.0.x dev version by composer. Next I made a server code:

$classLoader = new SplClassLoader('Wrench', __DIR__ . '/../lib');
$classLoader->register();
$server = new \Wrench\Server('ws://localhost:8000/');

$server->registerApplication('echo', new \Wrench\Application\EchoApplication());
$server->run();

I ran this in console and tried to connect in Chrome 27 using

var conn = new WebSocket('ws://localhost:8000');

But, sadly, I get response in console:

info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:42653 (101c8fe3ac6fe33db177c7df628a643c571a2f0ede17998b6598c5e94c9c5c44394ed05a0327b53e0d44011aee17cf269dab35ff1232778beb8fa98a18ef3e6f): Connected
warning: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\BadRequestException' with message 'Invalid application' in /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/Connection.php:234
Stack trace:
#0 /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/Connection.php(210): Wrench\Connection->handshake('GET / HTTP/1.1?...')
#1 /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/Connection.php(403): Wrench\Connection->onData('GET / HTTP/1.1?...')
#2 /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(245): Wrench\Connection->process()
#3 /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(172): Wrench\ConnectionManager->processClientSocket(Resource id #29)
#4 /home/szymon/projekty_www/ProjectManager/vendor/wrench/wrench/lib/Wrench/Server.php(201): Wrench\ConnectionManager->selectAndProcess()
#5 /home/szymon/projekty_www/ProjectManager/server/server.php(46): Wrench\Server->run()
#6 {main}

getClientId method missing

I notice that getClientId method does not exists. it can be created as alias of getId in Connection class.

SSL-Problem

Hello everybody,

i'm trying to set up a Websocket-Server using "wss"-protocol. Unfortunatetly even though i followed the instructions given in the other issues, i still get the following errors when i try to connect to the Server.

info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:59376 (ULajvFIuPPUTFpsJnvdre5Uhb0Glfgrbv1tyfRCYYfvDEwUrtQmL3II2Z3nzI6nzeBM42sg4JmdD9t0ttMOwfH): Connected
notice: Wrench\ConnectionManager: Client connection closed: exception 'Wrench\Exception\CloseException' with message 'Error reading data from socket: Not connected' in X:\xx\Wrench-master\lib\Wrench\Connection.php:400

As set up using the example given in server_ssl.php, except for the fact that i use a manually created certificate. I also fixed the bug mentioned in the previous issue concerning SSL-Problems.

has anyone an idea what is going wrong?

Errors on close connection

Hi,
If I close the connection in this way:

//var ws = new WebSocket('ws://10.150.10.150:8000/chat'); // WebSocket Client on Safari & Chrome
ws.send('close');

everything works as expected, but if I close this way:

ws.close();

I get the following error:

debug: Wrench\ConnectionManager: Wrench\Connection: 10.150.10.214:57853 (060db9ec24f6e7c68aad8f3b8181c6748f15092d891b8f8e724f76f07e8075a6f62a396a332542901943ed6ea3bf93c9cd4899af225670e3a3fb31d056ff5af1): Handling payload: 
warning: Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\ConnectionException' with message 'Unhandled payload type' in /home/desarrollos/sig2/library/Wrench/Connection.php:363
Stack trace:
#0 /home/library/Wrench/Connection.php(307): Wrench\Connection->handlePayload(Object(Wrench\Payload\HybiPayload))
#1 /home/library/Wrench/Connection.php(184): Wrench\Connection->handle('??rtj[')
#2 /home/library/Wrench/Connection.php(413): Wrench\Connection->onData('??rtj[')
#3 /home/library/Wrench/ConnectionManager.php(245): Wrench\Connection->process()
#4 /home/library/Wrench/ConnectionManager.php(172): Wrench\ConnectionManager->processClientSocket(Resource id #34)
#5 /home/library/Wrench/Server.php(200): Wrench\ConnectionManager->selectAndProcess()
#6 /home/application/run.php(86): Wrench\Server->run()
#7 {main}

Possibility to stop server

Right now if you start wrench server as $server->run() it launches an indefinite loop (while(true)). Only one way to stop it - kill the process.
What about to add user possibility to control it?
For example, I can write my own function, which listens process's signals or checks existing of some file. I want to pass this function to run() and stop looping when my function returns false.
For compatibility it could look like:

    public function run(callable $finish = null)
    {
       ...        
        if (!is_callable($finish) ) {
            $finish = function() { return true; };
        }        
        while ( $finish() ) {
            ...        
        }        
    }

Of course, I can create my own Server class (which extends main class) and redefine function run(). But I'm not sure, that it will be more correctly, than add native support.
@dominics what do you think? I would like to ask before making PR.

Flash Socket never initialize

Hi,

Your example work fine but once I put it on a website that has more Javascript on it the .swf never seem to initialize the socket. I have put some tracing and have found that FABridge__bridgeInitialized is never called. So far, at this moment I think that the swf cannot create the socket because the FABridge websocket is undefined. I am running the server with the client you provide in parallel with the integration on my website and the client works (so I know that the problem ain't on the server side).

Here is a trace log:

WebSocket constructor called web_socket.js (line 37)
SetTimeOutForCreation web_socket.js (line 44)
__initialize web_socket.js (line 308)
Flash location : WebSocketMain.swf web_socket.js (line 328)
Ready for : FABridge.addInitializationCallback web_socket.js (line 336)
addInitializationCallback>Bridgename:webSocket FABridge.js (line 88)
addInitializationCallback>inst defined FABridge.js (line 96)
addInitializationCallback>callbackList not null FABridge.js (line 102)

But in the same time, your example provide:

WebSocket constructor web_socket.js (line 37)
__initialize web_socket.js (line 308)
Flash location : WebSocketMain.swf web_socket.js (line 328)
Ready for : FABridge.addInitializationCallback web_socket.js (line 336)
addInitializationCallback>Bridgename:webSocket FABridge.js (line 88)
addInitializationCallback>inst defined FABridge.js (line 96)
addInitializationCallback>callbackList not null FABridge.js (line 102)
FABridge>AttachBridge from Initialized FABridge.js (line 132)
FABridge.attachBridge FABridge.js (line 184)
FABridge.attachBridge> #callbacks is : 1 FABridge.js (line 198)
[WebSocket] FABridge initializad web_socket.js (line 339)
SetTimeOutForCreation web_socket.js (line 44)
__createFlash web_socket.js (line 53)

I'll continue my investigation. If you have any idea it would be appreciate.

Frame handling causes crash

I'm not sure whether this is from a client trying to connect using an old version of the protocol, or some error on the server side, but whichever it is I think there should be some kind of check in place to prevent a crash.

I got the following error:

PHP Error[8]: Uninitialized string offset: 3
    in file /home/xxxx/Wrench/Frame/HybiFrame.php at line 273

This is because the code:

for ($i = $start; $i <= $end; $i++) {
    $length <<= 8;
    $length  += ord($this->buffer[$i]);
}

assumes that $this->buffer[$i] is set, but I can't see anything to guarantee this (apart from perhaps the specification of the protocol), so I think we should perhaps check that $this->buffer[$i] is set in each iteration.

SSL-Problem - Reopened

Hello,

the problem is unfotunately not fixed in Version 2.0.4. Therefore im Reopening my current problem.

The problem ist getting more important lately, because more an more browsers consider a connection from an SSL-Url to an "ws"-websocket as harmful and block it!

Original issue:

Hello everybody,

i'm trying to set up a Websocket-Server using "wss"-protocol. Unfortunatetly even though i followed the instructions given in the other issues, i still get the following errors when i try to connect to the Server.

info: Server initialized
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:59376 (ULajvFIuPPUTFpsJnvdre5Uhb0Glfgrbv1tyfRCYYfvDEwUrtQmL3II2Z3nzI6nzeBM42sg4JmdD9t0ttMOwfH): Connected
notice: Wrench\ConnectionManager: Client connection closed: exception 'Wrench\Exception\CloseException' with message 'Error reading data from socket: Not connected' in X:\xx\Wrench-master\lib\Wrench\Connection.php:400

As set up using the example given in server_ssl.php, except for the fact that i use a manually created certificate. I also fixed the bug mentioned in the previous issue concerning SSL-Problems.

has anyone an idea what is going wrong?

"Client connection closed" after handshake

Hello.
I'm trying to connect to my web socket server in PHP using your Client class. My code looks like this:
$uri = 'ws://hb-main.localhost:8000/tix_count';

require_once DIR . '/class/WebSocket/SplClassLoader.php';
$classLoader = new SplClassLoader('Wrench', DIR . '/class/WebSocket');
$classLoader->register();

$client = new \Wrench\Client($uri, 'http://hb-main.localhost');
$connect = $client->connect();

But each time I'm disconnecting after handshake, so output looks like this:
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:56887 (f1b15ee4fbadbd982b0d120116984121d1d98114fec4e04c3c8c2f3d0927fb09e3bfe1ff82ed9a75d82a9752d050b39f0159e6ac0bd2dcd7a0b2ff8593e09981): Connected
info: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:56887 (f1b15ee4fbadbd982b0d120116984121d1d98114fec4e04c3c8c2f3d0927fb09e3bfe1ff82ed9a75d82a9752d050b39f0159e6ac0bd2dcd7a0b2ff8593e09981): Handshake successful: 127.0.0.1:56887 (f1b15ee4fbadbd982b0d120116984121d1d98114fec4e04c3c8c2f3d0927fb09e3bfe1ff82ed9a75d82a9752d050b39f0159e6ac0bd2dcd7a0b2ff8593e09981) connected to /tix_count
notice: Wrench\ConnectionManager: Client connection closed: exception 'Wrench\Exception\CloseException' with message 'Error reading data from socket: Not connected' in /var/www/hb-main/inc/class/WebSocket/Wrench/Connection.php:396
Stack trace:
#0 /var/www/hb-main/inc/class/WebSocket/Wrench/ConnectionManager.php(243): Wrench\Connection->process()
#1 /var/www/hb-main/inc/class/WebSocket/Wrench/ConnectionManager.php(168): Wrench\ConnectionManager->processClientSocket(Resource id #34)
#2 /var/www/hb-main/inc/class/WebSocket/Wrench/Server.php(198): Wrench\ConnectionManager->selectAndProcess()
#3 /var/www/hb-main/inc/websocket/server.php(36): Wrench\Server->run()
#4 {main}

warning: Wrench\ConnectionManager: Wrench\Connection: 127.0.0.1:56887 (f1b15ee4fbadbd982b0d120116984121d1d98114fec4e04c3c8c2f3d0927fb09e3bfe1ff82ed9a75d82a9752d050b39f0159e6ac0bd2dcd7a0b2ff8593e09981): Unable to send close message

Why it's happening? Can you please fix this or let me know if I'm making mistake somewhere in my code.

Thank you.

Case sensitivity issue

I was trying the echo demo and it worked fine in the latest Chrome and Firefox. I tried it in IE10 and was getting an invalid upgrade header error.

I traced it to the upgrade header test on line 452 of Wrench/Protocol/protocol.php

if (!isset($headers[self::HEADER_UPGRADE])
                || $headers[self::HEADER_UPGRADE]) != self::UPGRADE_VALUE)
) {
            throw new BadRequestException('Invalid upgrade header');
}

What it came down to was IE was sending the "upgrade" header value as "Websocket" and the code was looking for "websocket". If I used strtolower() to create a case insensitive comparison, it worked with IE10.

I don't know if simply making the comparison case insensitive in that way would be the best way to fix the issue long term.

Full disclosure: I am a Microsoft employee, but I was teaching myself WebSockets for a personal project that will have a PHP backend, and was testing this on multiple browsers for that reason. I am not posting this in any official capacity.

send message from another PHP script

Hi Nico,

thanks for your websocket tool. I use the Echo application. I want to create a php file that connect to this application and I want it to send a message... I have the following script but I can't get it to work...

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$msg = 'hi';
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 8000);
socket_close($sock);
?>```

Can you help me?

Heder validation

Protocol.php on line 668 header validation invalid for headers such as:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: wA9isKYoy4/I5sZg9GadrE35X5A=

RFC 6455 support

Hello!
Do you panning to make support for last version of websocket - rfc6455? :)
Thank you.

No Origin Header

When I run a Wrench server (inside scripts of patternlab-php), it calls
$server = new \Wrench\Server('ws://0.0.0.0:'.$port.'/', array());
This starts the server, but it halts execution soon as a request is made, ending with a cascade of errors. I have pasted a screenshot of the exception reported.

I checked the HTML request being made, but couldn't get why Wrench wouldn't set the $origin variable

image

image

image

iPhone Protocol Version not Supported

Hello,

when connecting to php-websocket with an iPhone, then the Version is not supported.

I get this message in the Log output:
2012-06-13 14:06:56 [info] [client 192.168.178.93:49245] Unsupported websocket version

The Headers Sent by the Device are these:

( [Upgrade] => WebSocket [Connection] => Upgrade [Host] => 192.168.178.25:8000 [Origin] => http://192.168.178.25 [Sec-WebSocket-Key1] => 5#6u}35MJ)ubI7C41~5 3 [Sec-WebSocket-Key2] => h421 2271_71 G 0 )

Actualize examples

Hello guys.
Please, actualize your examples.

  • wrench/examples/server_ssl.php

It doesn't work, because it tries to register a demo application:
$server->registerApplication('demo', \Wrench\Application\DemoApplication::getInstance());
But there are no demo application in the folder:
$ ls Application.php EchoApplication.php ServerTimeApplication.php

  • wrench/examples/coffeescript/

There are no jsmaker.php (for coffescript convertion) and js files (json2 and jquery). But it isn't main problem. I can convert coffescript's files and add missing js. But it tries to connect to serverUrl = 'ws://127.0.0.1:8000/demo';
Could you help me and show a demo server script which I need to launch for this examples?

In summary I didn't find a good working example, therefore the understanding of your websocket realization is extremely difficult =(

Runtime Notice: Resource ID#144 used as offset, casting to integer (144) in WebSocket/Server.php line 38 (also, line 45)

The line in question:

$this->clients[$ressource] = $client;

where:

$ressource = socket_accept($this->master)

From the PHP manual:

is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.

Casting to int quietens the notice, and make the assumption about the resource type explicit.

Fatal Runtime Error On Unexpected Client Disconnection

Hi,

I have a fairly simple realtime game using Wrench and Msgpack, javascript client side and PHP back-end. The game itself works well in steady-state but in real world testing I have found alot of instances where if the client goes away, such as a user closes the tab, or reloads their tab in a browser (most testing is Chrome) the PHP daemon will crash:

Client 68.225.172.43:5177 joined game ws://192.99.44.xyz:1502#BESVL (2 players)
sendPacket exception: Socket is not connected
Got log level warning message Wrench\ConnectionManager: Wrench\Connection: 68.225.172.43:5177 (48ac8453791e1b01c876a918de88030b685c5cec9496904ca3e9af2c61512da67e4a1f32e6cc117dd6e45fe72bb4ac1d5340cfc793e0780378d0ffeee826eaf8): Unable to send close message
Client 68.225.172.43:5177 left game ws://192.99.44.xyz:1502#BESVL (1 players remaining)
Client 68.225.172.43:5177 disconnected
Got log level warning message Wrench\ConnectionManager: Error on client socket: exception 'Wrench\Exception\HandshakeException' with message 'Socket is not connected' in /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php:241
Stack trace:
#0 /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php(206): Wrench\Connection->handshake('GET /minimap HT...')
#1 /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php(399): Wrench\Connection->onData('GET /minimap HT...')
#2 /opt/dmr/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(243): Wrench\Connection->process()
#3 /opt/dmr/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(168): Wrench\ConnectionManager->processClientSocket(Resource id #44)
#4 /opt/dmr/vendor/wrench/wrench/lib/Wrench/Server.php(198): Wrench\ConnectionManager->selectAndProcess()
#5 /opt/dmr/server.php(20): Wrench\Server->run()
#6 {main}
Got log level warning message Wrench\ConnectionManager: Wrench\Connection: 68.225.172.43:5198 (67643d2ef47993810183eef1fc857b7178c3c4c1c37ea85fce3e2172ba7789e8154c005c86619706e395e4909f2f404a9e7473839144626a612b6602db7b64a2): Unable to send close message
Client 68.225.172.43:5198 disconnected

PHP Fatal error:  Call to a member function getRemainingData() on a non-object in /opt/dmr/vendor/wrench/wrench/lib/Wrench/Payload/Payload.php on line 169
PHP Stack trace:
PHP   1. {main}() /opt/dmr/server.php:0
PHP   2. Wrench\Server->run() /opt/dmr/server.php:20
PHP   3. Wrench\ConnectionManager->selectAndProcess() /opt/dmr/vendor/wrench/wrench/lib/Wrench/Server.php:198
PHP   4. Wrench\ConnectionManager->processClientSocket() /opt/dmr/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php:168
PHP   5. Wrench\Connection->process() /opt/dmr/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php:243
PHP   6. Wrench\Connection->onData() /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php:399
PHP   7. Wrench\Connection->handle() /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php:208
PHP   8. Wrench\Payload\PayloadHandler->handle() /opt/dmr/vendor/wrench/wrench/lib/Wrench/Connection.php:300
PHP   9. Wrench\Payload\Payload->receiveData() /opt/dmr/vendor/wrench/wrench/lib/Wrench/Payload/PayloadHandler.php:75

I have tried wrapping the entire server->run() in a try block to handle any exceptions, but the fatal runtime error is uncatchable (at least until PHP7 later this year, and I don't know what the Wrench library has planned for version support.)

Receiving error on Disconnection

I'm creating a simple Live Feed Application, Copying the ServeTimeApplication sample code, I'm receiving error on disconnection, when I check through Chrome console, I saw the following error:

WebSocket connection to 'ws://localhost:8000/test' failed: A server must not mask any frames that it sends to the client.

Any fix for this error?

Chrome version: 42

SSL problem

There is a problem in the code for the SSL, I created an auto-signed certificate and generated an .pem file. I try your example application Echo, it seems to contain problem in the code for ssl. Here's my code :

require_once 'D:\wamp\www\PrivateChat\lib\SplClassLoader.php';
$classLoader = new SplClassLoader("Wrench", "D:\wamp\www\PrivateChat\lib\\");
$classLoader->register();

use Wrench\BasicServer;

$server = new \Wrench\Server('wss://localhost:12345', array(
    'connection_manager_options' => array(
        'socket_master_options' => array(
            'server_ssl_cert_file' => 'D:\wamp\www\PrivateChat\cert\certificat.pem',
            'server_ssl_passphrase' => 'xavier2014epfctfe',
            'server_ssl_allow_self_signed' => true,
            'server_ssl_verify_peer' => false,
        ),
    )
));

$server->registerApplication('echo', new Wrench\Application\EchoApplication());
$server->run();

Client :

        websocket = new WebSocket("wss://localhost:12345/echo");
        websocket.onopen = function(ev) {
            alert('Connected');
        };

Errors:

*PHP Warning: stream_socket_accept(): failed to create an SSL handle in D:\wamp
www\PrivateChat\lib\Wrench\Socket\ServerSocket.php on line 87

*PHP Warning: socket_last_error() expects parameter 1 to be resource, boolean gi
ven in D:\wamp\www\PrivateChat\lib\Wrench\Socket\ServerSocket.php on line 90

*err: Socket error: exception 'Wrench\Exception\ConnectionException' with message
'Operation complete.
' in D:\wamp\www\PrivateChat\lib\Wrench\Socket\ServerSocket.php:90

options for ratelimiter problem

It seems, that RateLimiter in BasicServer is not configurable by parameters 'connections' ,'connections_per_ip','requests_per_minute'.

Original code ( BasicServer.php from line 29 ) :

    protected function configure(array $options)    {
        $options = array_merge(array(
            'check_origin'        => true,
            'allowed_origins'     => array(),
            'origin_policy_class' => 'Wrench\Listener\OriginPolicy',
            'rate_limiter_class'  => 'Wrench\Listener\RateLimiter'
        ), $options);

        parent::configure($options);
    }    protected function configureRateLimiter()
    {
        $class = $this->options['rate_limiter_class'];
        $this->rateLimiter = new $class();
        $this->rateLimiter->listen($this);
    }

Maybe here must be another option parameter like this:

Reworked code ( BasicServer.php from line 29 ):

    protected function configure(array $options)    {
        $options = array_merge(array(
            'check_origin'        => true,
            'allowed_origins'     => array(),
            'origin_policy_class' => 'Wrench\Listener\OriginPolicy',
            'rate_limiter_class'  => 'Wrench\Listener\RateLimiter'
            'rate_limiter_options'  => array()   // --------------------- ADDED
        ), $options);

        parent::configure($options);
    }
    protected function configureRateLimiter()    {
        $class = $this->options['rate_limiter_class'];
        $this->rateLimiter = new $class($this->options['rate_limiter_options']); // ------- ADDED
        $this->rateLimiter->listen($this);
    }

with defaults setup:

// Optional defaults for BasicServer RateLimiter:
//         'rate_limiter_class'  => 'Wrench\Listener\RateLimiter'
//         'rate_limiter_options'  => array();
//              'connections'         => 200, // Total
//              'connections_per_ip'  => 5,   // At once
//              'requests_per_minute' => 200  // Per connection
//     )

More over ... RateLimiter is not working at all:
Original code (ConnectionManager.php 235)

    protected function processClientSocket($socket)
    {
        $connection = $this->getConnectionForClientSocket($socket);

        if (!$connection) {
            $this->log('No connection for client socket', 'warning');
            return;
        }

        try {
            $connection->process();
        } catch (CloseException $e) {
            $this->log('Client connection closed: ' . $e, 'notice');
            $connection->close($e);
        } catch (WrenchException $e) {
            $this->log('Error on client socket: ' . $e, 'warning');
            $connection->close($e);
        }
    }

Reworkde code (ConnectionManager.php 235)

    protected function processClientSocket($socket)
    {
        $connection = $this->getConnectionForClientSocket($socket);

        if (!$connection) {
            $this->log('No connection for client socket', 'warning');
            return;
        }

        try {
        this->server->notify(Server::EVENT_CLIENT_DATA, array($socket, $connection));  // --------------------- ADDED
            $connection->process();
        } catch (CloseException $e) {
            $this->log('Client connection closed: ' . $e, 'notice');
            $connection->close($e);
        } catch (WrenchException $e) {
            $this->log('Error on client socket: ' . $e, 'warning');
            $connection->close($e);
        }
    }

Wrench / examples / server_ssl.php is wrong

Hi
First thank you for this exellennt simple websocket server, it works and it is really simple to manage.

I am trying the ssl example server but the provided example has a configuration issue:
this line
$server = new \Wrench\Server('localhost', 8000, 'ssl', '/etc/pki/tls/certs/ca.crt', null);

Should be:
$server = new \Wrench\Server('localhost:8000:',
array(.....) );

Thanks
Alban

jitt.li source

I'd love to see the code behind jitt.li. Any chance you can add it to a repo? I love learning by example. :)

sending data directly after connection

I've a strange behavior with this simple client (in JS) :

    var socket = new WebSocket("ws://localhost:8000/test");

    socket.onopen = function() {
        console.log('onopen');
        socket.send('AUTH: { "username": "plop", "password": "plop"}');
    }

    socket.onmessage = function(data) {
        console.log('onmessage '+data);
    }

    socket.onclose = function() {
        console.log('onclose');
    }

    socket.onerror = function() {
        console.log('onerror');
    }

This code is pretty basic but server doesn't receive the AUTH message. Handshake is done but no message received. But if i do this, the server receives the first AUTH (not the second) :

    socket.onopen = function() {
        console.log('onopen');
        socket.send('AUTH: { "username": "plop", "password": "plop"}');
        socket.send('AUTH: { "username": "plop", "password": "plop"}');
    }

I've tested with Chrome 19 and Firefox 14. When closing the tab in Chrome, CloseException is received and the server never got the AUTH message. When closing the tab with Firefox, the server receives the AUTH message and CloseException comes after +/- 30 seconds.

I can provide the server that i use (that is pretty simple too).

Thanks

stream_socket_accept(): Unable to set local cert chain file, failed to create an SSL handle, Failed to enable crypto

Using:

wrench/wrench, version v2.0.7, via Composer.

I've been testing for a while the creation of a Secure Websocket server. I have tested that from my website with no problems, it uses a valid certificate. But a friend of mine is trying to do the same with his valid certificate with no good results.

I helped him to create the secure websocket with Wrench, the PEM certificate was correctly created and the php script has the correct path.

When I start the php script it does not report any problem, it just says the server was initialized. But when the first connection from the browser arrives, it fails with this error message:

root@thedomain:~/websockettest# php secure_server.php
info: Server initialized
PHP Warning:  stream_socket_accept(): Unable to set local cert chain file `/root/.ssl/thedomain.net/2/thedomain.net.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87

Warning: stream_socket_accept(): Unable to set local cert chain file `/root/.ssl/thedomain.net/2/thedomain.net.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87
PHP Warning:  stream_socket_accept(): failed to create an SSL handle in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87

Warning: stream_socket_accept(): failed to create an SSL handle in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87
PHP Warning:  stream_socket_accept(): Failed to enable crypto in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87

Warning: stream_socket_accept(): Failed to enable crypto in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87
PHP Warning:  stream_socket_accept(): accept failed: Success in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87

Warning: stream_socket_accept(): accept failed: Success in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 87
PHP Warning:  socket_last_error() expects parameter 1 to be resource, boolean given in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 90

Warning: socket_last_error() expects parameter 1 to be resource, boolean given in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php on line 90
err: Socket error: exception 'Wrench\Exception\ConnectionException' with message 'Success' in /root/websockettest/vendor/wrench/wrench/lib/Wrench/Socket/ServerSocket.php:90
Stack trace:
#0 /root/websockettest/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(183): Wrench\Socket\ServerSocket->accept()
#1 /root/websockettest/vendor/wrench/wrench/lib/Wrench/ConnectionManager.php(166): Wrench\ConnectionManager->processMasterSocket()
#2 /root/websockettest/vendor/wrench/wrench/lib/Wrench/Server.php(198): Wrench\ConnectionManager->selectAndProcess()
#3 /root/websockettest/secure_server.php(41): Wrench\Server->run()
#4 {main}

The certificate PEM file is in the correct path:

root@thedomain:~/websockettest# ls -al /root/.ssl/thedomain.net/2/thedomain.net.pem
-rwxrwxrwx 1 root root 3602 Dec  9 14:15 /root/.ssl/thedomain.net/2/thedomain.net.pem

That PEM file was created with:

cat thedomain.net.crt thedomain.net.key > thedomain.net.pem

The Key file has no Passphrase.

Here is the secure_server.php content:

#!/usr/bin/env php
<?php

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

require_once "vendor/autoload.php";

$pemFile = '/root/.ssl/thedomain.net/2/thedomain.net.pem';
$pemPassphrase = '';

//$websocketUrl = 'wss://thedomain.net:3001/'; // We used this one, but it fails.
$websocketUrl = 'wss://0.0.0.0:3001/';

// User can use tls in place of ssl
$server = new \Wrench\Server($websocketUrl, array(
    'connection_manager_options' => array(
        'socket_master_options' => array(
            'server_ssl_local_cert'        => $pemFile,
            'server_ssl_passphrase'        => $pemPassphrase,
            'server_ssl_allow_self_signed' => true,
            'server_ssl_verify_peer'       => false,
        )
    )
));

$server->registerApplication('echo', new \Wrench\Application\EchoApplication());
$server->registerApplication('time', new \Wrench\Application\ServerTimeApplication());
$server->run();

For better compatibility, we created a simple apache with SSL on the same machine, and we changed the default index.html to have a very simple echo websocket client connecting to this server. Of course, we added SSL support by using the very same certificate (crt, key, ca_bundle).

I tried all of this with my domain and certificate and it works correctly.

Both certificates were issued by the same company and both are of the same type/class, generated only with a few days of difference.

Is there anything wrong with the secure_server.php script, or perhaps there is any kind of problem with PHP socket functions and how it handles certain certificates?

My webpage with the echo test working is here: [https://jdzb.org/servicios/testwebsockets]. This one works fine.

To test the failing service, right now it is not pointed by the domain, but please add to your host file ("/etc/hosts" in linux, "C:\Windows\System32\drivers\etc\hosts" in windows) the following:

104.236.0.50    ecompound.net

Then access [https://ecompound.net] to test it, although tis page will only display "DISCONNECTED {} Error undefined". The browser console shows:

WebSocket connection to 'wss://ecompound.net:3001/echo' failed: Error in connection establishment: net::ERR_CONNECTION_RESET

Any help is highly appreciated.

UPDATE 01

We have some other ssl certificates available, and we have tested some of those with success, but if we try to connect to the same page from an iPad, somehow it fails, as if there were incompatibility issues between the iPad and the secure websocket server with certain certificates. Again, for this case from an iPad the echo test in my site [https://jdzb.org/servicios/testwebsockets] works correctly, but it has failed from other ssl certificates that are considered valid by all mayor PC web browsers.

Security considerations: Allowing client side to post directly to websocket is insecure

How about creating a "write key", similar to what pusher.js does with their websocket api. this means server side scripts only have access to write to the socket, preventing malicious users from submitting messages to the socket directly from the js console. It's pretty alarming that there isn't an open source library with this functionality, but i suppose it would be pretty easy to add on top of the basic server example, though i think it should be mandatory part of the library anyway. What do you think about it? There are alot of newbs to websockets out there who can easily step into the beartrap of an insecure websocket, and depending on what kind of data they are sending accross the wires it could have bad consequences.

TLS/SSL sockets not working

I'm unable to say where this problem comes from (it could indeed be as a result of my personal setup).

I'm using Wrench as is, to set up a secure web sockets server.
My configuration is the following:

$server = new \Wrench\Server('wss://127.0.0.1:8000/', array(
    'connection_manager_options' => array(
        'socket_master_options' => array(
            'ssl_cert_file' => path/to/my/cert',
            'ssl_passphrase' => 'certPassPhrase',
            'ssl_allow_self_signed' => true,
            'ssl_verify_peer' => false,
        ),
    ),
));
$server->registerApplication('echo', new \Wrench\Application\EchoApplication());
$server->run();

If I use a ws uri (as opposed to a wss uri), everything works fine, and I can connect to the local web sockets server, and receive echo feedback.
However, if I use wss, the server initialises without a problem, but whenever I attempt to make a web sockets connection then I get the following error: stream_socket_accept(): SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used. This could be because the server is missing an SSL certificate (local_cert context option). I get this same error if I attempt to make a simple SSL connection using command line openssl.

At first glance it would seem that it is simply not finding the certificate file, but I don't think this is the case. I have logged the uri and stream options that are used to create the master socket, and they are exactly the same as those that I use in a simple script that uses the same socket stream functions to open a stream on the same uri and echo back input, and that script works without a problem (using openssl command line, I see that an SSL connection is established, and can enter text which is sent back by the server).

I also tried using the accompanying SSL helper class to generate a certificate file, just in case, but with the same result.

So, it may be that this is still a configuration problem on my part, but I really can't see where, all the more so since I am imitating the same stream functions but with a positive result in my other script. If there is any light anyone can throw on this, or any working SSL example I can test, then I would be grateful...

Undefined method

In Client.php on method "sendData" line 135 used undefined method "encode"

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.