Giter Site home page Giter Site logo

websocket-php's Introduction

Websocket Client and Server for PHP

Build Status Coverage Status

Archived project

This project has been archived and is no longer maintained. No bug fix and no additional features will be added.
You won't be able to submit new issues or pull requests, and no additional features will be added

This library has been replaced by sirn-se/websocket-php

Websocket Client and Server for PHP

This library contains WebSocket client and server for PHP.

The client and server provides methods for reading and writing to WebSocket streams. It does not include convenience operations such as listeners and implicit error handling.

Documentation

Installing

Preferred way to install is with Composer.

composer require textalk/websocket
  • Current version support PHP versions ^7.4|^8.0.
  • For PHP 7.2 and 7.3 support use version 1.5.
  • For PHP 7.1 support use version 1.4.
  • For PHP ^5.4 and 7.0 support use version 1.3.

Client

The client can read and write on a WebSocket stream. It internally supports Upgrade handshake and implicit close and ping/pong operations.

$client = new WebSocket\Client("ws://echo.websocket.org/");
$client->text("Hello WebSocket.org!");
echo $client->receive();
$client->close();

Server

The library contains a rudimentary single stream/single thread server. It internally supports Upgrade handshake and implicit close and ping/pong operations.

Note that it does not support threading or automatic association ot continuous client requests. If you require this kind of server behavior, you need to build it on top of provided server implementation.

$server = new WebSocket\Server();
$server->accept();
$message = $server->receive();
$server->text($message);
$server->close();

License and Contributors

ISC License

Fredrik Liljegren, Armen Baghumian Sankbarani, Ruslan Bekenev, Joshua Thijssen, Simon Lipp, Quentin Bellus, Patrick McCarren, swmcdonnell, Ignas Bernotas, Mark Herhold, Andreas Palm, Sören Jensen, pmaasz, Alexey Stavrov, Michael Slezak, Pierre Seznec, rmeisler, Nickolay V. Shmyrev, Christoph Kempen, Marc Roberts, Antonio Mora, Simon Podlipsky, etrinh.

websocket-php's People

Contributors

amoraaluxion avatar armen avatar fiddur avatar jaytaph avatar krydos avatar larsgust avatar logioniz avatar manuelm avatar marcroberts avatar markherhold avatar matias-pool avatar nshmyrev avatar peterjah avatar pmccarren avatar quentinbellus avatar raoh avatar rmeisler avatar rmeisler-applovin avatar robquistnl avatar simpod avatar sirn-se avatar slezakattack avatar sloonz avatar swmcdonnell avatar vkuptcov avatar waldyrious avatar webpatser avatar zapling 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  avatar

websocket-php's Issues

LICENSE missing

Without a license, it is copyrighted material not legal to copy.

I suggest the ISC license. Also add 2 lines in each file, e.g.

// Copyright 2014-2015 Textalk AB
// This file is part of websocket-php and subject to the ISC license.

Simple test blocks?

When I try the simple test under Client usage in the readme I never see 'Will output 'Hello WebSocket.org!'.

Same goes when I try against my own Ratchet server.

It seems like the code stalls on the send call?

guide to Laravel? Not really an issue

Hi There

Could you give an install guide for laravel as this seems to be the framework of choice these days,
as laravel does the auto loading would be super helpful thanks :)

Any option to simulate in one env?

I wanted to make some local tests for socket works and found that message pong sent for response on message ping also coming to the same stream and server think that pong is also came from client, but it is incorrect.

How to set Sec-WebSocket-Protocol

i try to use websocket-php to connect to a loxone miniserver.
they say in the api to specify Sec-WebSocket-Protocol -> remotecontrol​ when connecting.

so is ist possible so set a Sec-WebSocket-Protocol?

thanks

Again, «Empty read; connection dead? ...»

Hello. Can you help me, plz? 😰

PHP 7.3.2,
textalk 1.3.1
<?php

// ini_set('max_execution_time', 0);

require 'vendor/autoload.php';
require 'variables.php';

use GuzzleHttp\Client;
use WebSocket\Client as WebSocket;

$client = new GuzzleHttp\Client();
$res = $client->request('GET', $base_uri . 'user/oauth', [
  'verify' => false,
  'headers' => [
    'Authorization' => 'Bearer ' . $user_token,
  ],
]);

if ($res->getStatusCode() === 200) {
  $respObjDecoder = json_decode($res->getBody(), 0)->data;

  $clientWebSoket = new WebSocket(
    'wss://centrifugo.donationalerts.com/connection/websocket'
  );

  $clientWebSoket->send(
    '{"params": {"token": "' .
      $respObjDecoder->socket_connection_token .
      '"},"id": ' .
      $respObjDecoder->id .
      '}'
  );

  $respObjDecoderMessage = json_decode($clientWebSoket->receive(), 0)->result
    ->client;

  $arrayToPrep = [
    'channels' => ['$alerts:donation_' . $respObjDecoder->id],
    'client' => $respObjDecoderMessage,
  ];

  $res = $client->request('POST', $base_uri . 'centrifuge/subscribe', [
    'verify' => false,
    'json' => $arrayToPrep,
    'headers' => [
      'Authorization' => 'Bearer ' . $user_token,
    ],
  ]);

  $respObjChannels = json_decode($res->getBody(), 0)->channels[0];

  $clientWebSoket->send(
    '{"params": {
        "channel": "' .
      $respObjChannels->channel .
      '",
        "token": "' .
      $respObjChannels->token .
      '" },
    	"method": 1,
    	"id": 2
}'
  );

  # start to listening ¯\_(ツ)_/¯

  while (true) {
    try {
      $message = $clientWebSoket->receive();
      echo $message;
    } catch (\WebSocket\ConnectionException $e) {
      echo $e;
    }
  }
  $clientWebSoket->close();
}

I get a response from the server:

{"id":2,"result":{"recoverable":true,"seq":11,"epoch":"1589467947"}}
{"result":{"type":1,"channel":"$alerts:donation_424675","data":{"info":{"user":"820","client":"21434006-8483-4f96-870u-92c0c7cea1ff"}}}}

Then,

WebSocket\ConnectionException: Empty read; connection dead?  Stream state: {"crypto":{"protocol":"TLSv1.2","cipher_name":"ECDHE-RSA-AES256-GCM-SHA384","cipher_bits":256,"cipher_version":"TLSv1.2"},"timed_out":true,"blocked":true,"eof":false,"stream_type":"tcp_socket\/ssl","mode":"r+","unread_bytes":0,"seekable":false} in C:\OServer\domains\alerts\vendor\textalk\websocket\lib\Base.php:298
Stack trace:
#0 C:\OServer\domains\alerts\vendor\textalk\websocket\lib\Base.php(159): WebSocket\Base->read(2)
#1 C:\OServer\domains\alerts\vendor\textalk\websocket\lib\Base.php(149): WebSocket\Base->receiveFragment()
#2 C:\OServer\domains\alerts\index.php(69): WebSocket\Base->receive()
#3 {main}

If I turn off error output:

catch (\WebSocket\ConnectionException $e) { }

Result in console:

{"id":2,"result":{"recoverable":true,"seq":11,"epoch":"1589467947"}}
{"result":{"type":1,"channel":"$alerts:donation_424675","data":{"info":{"user":"820","client":"21434006-8483-4f96-870u-92c0c7cea1ff"}}}}
ping

Sorry for my bad English 😶

This library is prepared for node.js server?

I am trying to send something to node.js socket.io running server, but no chance.

php index.php

Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Connection to 'ws://localhost/' failed: Se
rver sent invalid upgrade response:
' in X:\srv\git.romanmatena.cz\solis5-advanced\websocket-php-client\vendor\textalk\websocket\lib\Client.php:149
Stack trace:
#0 X:\srv\git.romanmatena.cz\solis5-advanced\websocket-php-client\vendor\textalk\websocket\lib\Base.php(48): WebSocket\C
lient->connect()
#1 X:\srv\git.romanmatena.cz\solis5-advanced\websocket-php-client\index.php(10): WebSocket\Base->send('Hello WebSocket..
.')
#2 {main}
  thrown in X:\srv\git.romanmatena.cz\solis5-advanced\websocket-php-client\vendor\textalk\websocket\lib\Client.php on li
ne 149

trouble installing with composer

I've having trouble installing this with composer, can you give me good example and update the readme? I would like to try this, cheers.

Subscribe

Is it possible to subscribe to a channel via this library ?

Exception with ratchet server

Hello,

I have a crash when I try to connect with a ratchet server (dev-master version).

Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Connection to 'ws://192.168.56.101/test/-1' failed: Server sent invalid upgrade response:
HTTP/1.1 101 Switching Protocols

My client code:

$wsclient = new Client("ws://192.168.56.101:4242/test/-1");
$arrayToSend = [
        'id' => $archiveId,
        'status' => 0
];
$wsclient->send(json_encode($arrayToSend));

My ratchet server code:

$app = new Ratchet\App('192.168.56.101', 4242, '0.0.0.0');
$app->route('/test/{id}', new CommonDashboard\webSocket\TestWebSocket(), array('*'));
$app->run();

Do you have any ideas for fixing that ?
Thank ;)

Client doesn't know when the server closed the stream and throws an exception

It took me a while to understand this, so I will leave this as a note for others:

My usecase: I use this library to interact with the Chrome DevTools. When I close a target (like a tab), Chrome closes the websocket stream automatically. When I try to close the websocket stream via the close() function, the client will throw an exception. I would expect that the close() function ignores an already closed stream, but instead it will try to write a 'closing frame' to it and fail.

The WebSocket\Client won't notice when the server closes the websocket.

Instead it will throw a WebSocket\ConnectionException with a message like

Empty read; connection dead? Stream state: {"timed_out":false,"blocked":true,"eof":true,"stream_type":"tcp_socket/ssl","mode":"r+","unread_bytes":0,"seekable":false}

The important part is eof:true which means that the stream was closed.

Example: Start a websocket server and connect to it. While the client is connected, kill the server and inspect the client. Its member $is_connected is still true. Try to perform any action (ie. write or close) and it will throw the exception.

timeout option is actually doesn't applied to underlying stream

Even if you have provided timeout value to the WebSocket\Client class it doesn't applied to the socket stream and therefore is only used as a connect timeout.

IMO it's more important to apply it as timeout for read from socket which is done by calling setTimeout function.

I propose to call setTimeout in constructor:
InnovaCo@30381c2

Listening client

It doesn't seem to be possible to make a client that just sends once and listens after that. Am I missing something?

run the client is fail

Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Empty read; connection dead? Stream state: {"timed_out":false,"blocked":true,"eof":true,"stream_type":"tcp_socket/ssl","mode":"r+","unread_bytes":0,"seekable":false}'

Empty read; connection dead? Stream state: {"timed_out":true,"blocked":true,"eof":false,"stream_type":"tcp_socket\/ssl","mode":"r+","unread_bytes":0,"seekable":false}

$ws_url = config(ENVIRONMENT . '.page_ws_url');
$str = '{"req":"market.' . $symbol . '.kline.1min","id":' . microtime(true) . ',"from":' . time() . ',"to":' . time() . '}' . "\r\n";
try {
$client = new \WebSocket\Client($ws_url);
$client->send($str);
$data = $client->receive();
$list = json_decode(gzdecode($data), true);
if (isset($list['status']) && ($list['status'] === 'ok')) {
$end = end($list['data']);
$newprice = $end['close'];
}
} catch (RequestException $e) {
if ($e->hasResponse()) {
$mark = $e->getResponse()->getBody()->getContents();
} else {
$mark = $e->getMessage();
}
Log::info($ws_url);
Log::info($mark);
}

[0] ConnectionException in Base.php line 269
Empty read; connection dead? Stream state: {"timed_out":true,"blocked":true,"eof":false,"stream_type":"tcp_socket/ssl","mode":"r+","unread_bytes":0,"seekable":false}

Getting fatal error on travis CI

PHP Fatal error: Uncaught Behat\Testwork\Call\Exception\CallErrorException: Warning: fwrite() expects parameter 1 to be resource, null given in /home/travis/build/acquia-pso/bayah/vendor/textalk/websocket/lib/Base.php line 246 in /home/travis/build/acquia-pso/bayah/vendor/behat/behat/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php:85
Stack trace:
#0 [internal function]: Behat\Testwork\Call\Handler\RuntimeCallHandler->handleError(2, 'fwrite() expect...', '/home/travis/bu...', 246, Array)
#1 /home/travis/build/acquia-pso/bayah/vendor/textalk/websocket/lib/Base.php(246): fwrite(NULL, '\x81\xB3\xC8\xCD\x80,\xB3\xEF\xE9H\xEA\xF7\xB1\x1D\xFD...')
#2 /home/travis/build/acquia-pso/bayah/vendor/textalk/websocket/lib/Base.php(126): WebSocket\Base->write('\x81\xB3\xC8\xCD\x80,\xB3\xEF\xE9H\xEA\xF7\xB1\x1D\xFD...')
#3 /home/travis/build/acquia-pso/bayah/vendor/textalk/websocket/lib/Base.php(70): WebSocket\Base->send_fragment(true, '{"id":11541,"me...', 'text', true)
#4 /home/travis/build/acquia-pso/bayah/vendor/dmore/chrome-mink-d in /home/travis/build/acquia-pso/bayah/vendor/behat/behat/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php on line 85

PHP7 Support

It seems like there is no support in PHP7.
Am I'm missing something.

Client->send should always be masked

Hello. Thank you for so good library.
I just trying to use WebSocket\Client class but I got the issue.

When I'm trying to connect to my websocket server (nodejs) I got the connection (I see it in the nodejs log). But when I'm trying to send something to the my websocket server I got nothing on the websocket server side.

Here is code of websocket server side. I just printing to the console every time when WebSocket client trying to send text.

        conn.on("text", function (str) {
            console.log('got message => ', str);
        }

This code works on %100 because this code works when I'm using browser.

Thank you so much and I'm sorry for my English.

Any example with AWS Appsync's graphql subscription

Can anyone help me with a working example of graphql subscription with php5 and AWS Appsync or php5 WebSocket client which works with Appsync? I am trying textalk but haven't got any success.

<?php
require(dirname(dirname(__FILE__)) . '/graphql/vendor/autoload.php');

use WebSocket\Client;

$query = <<<'GRAPHQL'
subscription onCreateProfile{
  onCreateBatch {
    hotelId
    batchId
    profiles {
      id
    }
  }
}
GRAPHQL;

$appSyncURL = 'wss://pbnblnr7xxxxxxxxxxxx.appsync-realtime-api.ap-south-1.amazonaws.com/graphql';
$context = stream_context_create();
stream_context_set_option($context, 'ssl', 'verify_peer', false);
stream_context_set_option($context, 'ssl', 'verify_peer_name', false);
$client = new WebSocket\Client($appSyncURL, [
    'timeout' => 60, // 1 minute time out
    'context' => $context,
    'headers' => [
        'x-api-key' => 'APIKEY',
    ],
]);
$client->send($query);
echo $client->receive();
$client->close();

Running above snippet gives below error:

$ php subscription.php
{"payload":{"errors":[{"message":"NoProtocolError","errorCode":400}]},"type":"connection_error"}PHP Fatal error:  Uncaught WebSocket\ConnectionException: Empty read; connection dead?  Stream state: {"crypto":{"protocol":"UNKNOWN","cipher_name":"TLS_AES_256_GCM_SHA384","cipher_bits":256,"cipher_version":"TLSv1.3"},"timed_out":false,"blocked":true,"eof":true,"stream_type":"tcp_socket\/ssl","mode":"r+","unread_bytes":0,"seekable":false} in /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php:316
Stack trace:
#0 /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php(299): WebSocket\Base->throwException('Empty read; con...')
#1 /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php(159): WebSocket\Base->read(2)
#2 /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php(149): WebSocket\Base->receiveFragment()
#3 /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php(272): WebSocket\Base->receive()
#4 /var/www/html/demo/graphql/subscription.php(31): WebSocket\Base->close()
#5 {main}
  thrown in /var/www/html/demo/graphql/vendor/textalk/websocket/lib/Base.php on line 316

So has anyone tried graphQL subscriptions with php5? My requirement is to consume Graphql Subscription in PHP application (in backend). I know graphQL subscription would work fine in frontend through javascript WebSocket client. But I've to use graphql subscriptions in PHP5 application.

Any help will be appreciated!

Listening to a Websocket Server?

Hi there! I'm trying to build a client that will listen to a Websocket server and respond when the server sends an event. I tried doing this (not sure if it's the correct way to do it)

$client = new Client('ws://<server>');
while (1) {
            $message = $client->receive();
            if ($message) {
                $messageObject = json_decode($message);
                //do something, such as print to console
            }
}

But it would miss messages sometimes and after about ten minutes of inactivity from the server, it would die with this error:

[WebSocket\ConnectionException]                                                                                                                 
  Empty read; connection dead?  Stream state: {"timed_out":true,"blocked":true,"eof":false,"stream_type":"tcp_socket\/ssl","mode":"r+","unread_b  
  ytes":0,"seekable":false}

Am I doing this incorrectly?

Thanks in advance

Cannot connect to secure WSS

Connecting to ws:// works fine but when I use wss:// to the same server (which works just fine in the browser and a websocket tester) it fails:

PHP Fatal error:  Uncaught WebSocket\ConnectionException: Could not open socket to "mydomain.com:443":  (0). in C:\...\includes\composer_libs\textalk\websocket\lib\Client.php:95
Stack trace:
#0 C:\...\includes\composer_libs\textalk\websocket\lib\Base.php(48): WebSocket\Client->connect()
#1 C:\...\run.phpcli(22): WebSocket\Base->send('{"action":"play...')
#2 {main}
  thrown in C:\...\includes\composer_libs\textalk\websocket\lib\Client.php on line 95

Fatal error: Uncaught WebSocket\ConnectionException: Could not open socket to "mydomain.com:443":  (0). in C:\...\includes\composer_libs\textalk\websocket\lib\Client.php on line 95

WebSocket\ConnectionException: Could not open socket to "mydomain.com:443":  (0). in C:\...\includes\composer_libs\textalk\websocket\lib\Client.php on line 95

Call Stack:
    0.2077     355880   1. {main}() C:\...\run.phpcli:0
    0.2148     587168   2. WebSocket\Base->send() C:\...\run.phpcli:22
    0.2148     587200   3. WebSocket\Client->connect() C:\...\includes\composer_libs\textalk\websocket\lib\Base.php:48

Any idea what the problem can be?

The server uses Apache modules proxy and proxy_wstunnel to make the secure connection (followed https://stackoverflow.com/questions/16979793/php-ratchet-websocket-ssl-connect#28393526). Internally the websocket server runs on a port above 8000.

Help me....Why is it pending for?

my php code..
always pending....
why????

help me!please....
`<?php

require('../vendor/autoload.php');

use WebSocket\Client;
ini_set("max_execution_time", "3600");
$client = new Client("ws://127.0.0.1:9503");
$client->send("Hello from PHP");
echo $client->receive() . "\n"; // Should output 'Hello from PHP'`

fwrite error on version 1.2.0

getting this error message when continually sending one command every 2 seconds:
fwrite(): send of 15 bytes failed with errno=32 Broken pipe in /var/www/html/Mediatrix/php/vendor/textalk/websocket/lib/Base.php on line 179
PHP Fatal error: Uncaught WebSocket\ConnectionException: Could only write 0 out of 15 bytes. in /var/www/html/Mediatrix/php/vendor/textalk/websocket/lib/Base.php:182

How to send a ping every x seconds?

I use the gardena websocket (smart API) which closes the connection every 200 seconds even I send no ping message.
How can I get this work?

Verify that stream_socket_client function is available / enabled in client

We had a developer integrating this library into a larger project, and they were hitting a ConnectionException with the message about not being able to connect to the given host/port, but that the $errno and $errstr that were supposed to be printed out were blank. They did not know what to do as connecting to the client via python / JS was working fine. As it turns out, the project had set-up a disabled PHP functions list that included stream_socket_client which was causing the function to silently fail with no error.

To help others, would it be helpful to check (either within constructor or at global scope above class definition) that stream_socket_client is not disabled, doing something like:

if (!function_exists('stream_socket_client')) {
    throw new Exception('stream_socket_client is disabled');
}

Happy to open a PR for this if desired (with clarification as to where such a check might live), though not sure how one might write a unit test for it.

Unable to send and receive messages

I am using Rachet Library to create a WebSocket Server. I am connecting that server as:

use WebSocket\Client;
$client_wa = new Client("ws://localhost:9000");
$client_wa->send("Hello WebSocket.org!");
print_r($client_wa);

At server end I am not getting message neither I am getting message from server. Issue is not with Server as my web client works fine. My server logic is given as:

public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        print "WA got the message:- ".$msg;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from === $client) {
                $msg = 'WA Server responds:- '.$msg;
                $client->send($msg);
            }
        }
    }

It does connect as it does indicate when the client dies.

WAMP sub-protocol

FYI / "Feature Request"

Found textalk/websocket-php when searching for a WAMP client that didn't have stacks and stacks of dependencies and are only meant to be incorporated in command-line scripts.

By using texttalk/websocket-php and performing a simple little handshake on connection I was able to build a basic WAMP client for the single purpose of for pushing "messages"/data to a WAMP server.
(I have no need for "subscribing" to WAMP topics or remote procedure calls)

https://github.com/bkdotcom/WampPublisher

Feel free to borrow/incorporate it into this project.

Websocket connection does not seem to be persistent

I observe the following behaviour in my application -

1.) the client connects to a server through a websocket
2.) the client receives a message from the server, and answers
3.) the server loses connection to the client

optimally, I would like to keep the connection open, because my communication is not stateless, can I do that? =)

Thanks

How to debug SSL issues...

We use WSS because SSL is a must...

I have clients without "trusted root certs", I typically fix this by downloading cacerts.pem from here https://curl.haxx.se/docs/caextract.html and configuring PHP accordingly.

However, if you do not know that there might be an issue with a certificate, then thw following message (everyting you will see) is not helpful:

Could not open socket to "HOSTNAME:8080": (0). ["[object] (WebSocket\ConnectionException(code: 0): Could not open socket to "HOSTNAME:8080": (0). at .../websocketserver/vendor/textalk/websocket/lib/Client.php:95)"

Is there a way to get a more detailled message what is wrong? I mean... I know now that I have to check if is the certificate - but does everybody else?

feature request: Client destructor - option to keep socket open

https://github.com/Textalk/websocket-php/blob/master/lib/Client.php#L37

class Client extends Base

class Base {

  public function __destruct() {
    if ($this->socket) {
      if (get_resource_type($this->socket) === 'stream') fclose($this->socket);
      $this->socket = null;
    }
  }

}

PHP Warning: fwrite() expects parameter 1 to be resource, null given in vendor/textalk/websocket/lib/Base.php on line 251

PHP Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Could only write out of 557 bytes.' in vendor/textalk/websocket/lib/Base.php:256

I have encountered an object destructing and attempting to send a message after WebSocket/Client's destructor (It's an Error notification system)..

would be nice to have a 'destruct' : false (default: true) option to not close the socket / don't set to null in __destruct

  public function __destruct() {
    if ($this->options['destruct'] && $this->socket) {
      if (get_resource_type($this->socket) === 'stream') fclose($this->socket);
      $this->socket = null;
    }
  }

WSS connection fails on OpenWRT with Linux 4 Kernel and PHP 5.6.16

Client works perfectly on OpenWRT with Linux Kernel 3.10.49 and PHP 5.4.38.

But fails when upgraded to Linux 4.1.13 and PHP 5.6.16 on OpenWRT with:

Fatal error: Uncaught exception 'WebSocket\ConnectionException' with message 'Could not open socket to "myserver.com:443": (0).' in /www/ws/lib/Client.php:65
Stack trace:
#0 /www/ws/lib/Base.php(122): WebSocket\Client->connect()
#1 /www/ws/wsclient.php(38): WebSocket\Base->receive()
#2 {main}

thrown in /www/ws/lib/Client.php on line 65

Runs fine though on Ubuntu with Kernel 3.16.7 and PHP 5.6.20.

Headers are slightly wrong, but easy to fix

I'm using this client with the server from here https://github.com/nekudo/php-websocket in a specialized setup. (doing 3. party authentication integration inside the handshake process of websockets.

I noticed that the handshake headers are all in lowercase, and in my case the server does not support that.
Doing a quick read on the spec from https://tools.ietf.org/html/rfc6455 I haven't been able narrow down if this is in the specification, but they do spell the header names with some upper case letters.

So I assume it is "more correct" to do use a case sensitive approach, although it might be optional in the docs.

I have done a "case sensivity" fix allowing me to use the project with nekudu websocket.
Line 107 in client.php
$headers = array( 'Host' => $host . ":" . $port, 'User-agent' => 'websocket-client-php', 'Connection' => 'Upgrade', 'Upgrade' => 'websocket', 'Sec-WebSocket-Key' => $key, 'Sec-WebSocket-Version' => '13', );

Abandoned project

I see that there are no committees for more than a year and that issues are not being solved. Is this project abandoned?

Need to call receive on the Client before my WCF server receives the call

Thanks for this repo. Glad I finally could find something sane and solid that wasn't built upon stacks of stacks of dependencies.

I have the following code that works:

$client = new Client("ws://localhost/WCFWebSocketService.svc");
$client->send('{ "Message": { "Text": "Sent from PHP", "ToGroup": "All", "ToUsername": "User" } }');

echo $client->receive();

However this call is a one-way call where I don't get a return message and I also don't particularly care about what the server does with what I send to it until it's processed async later on.

If $client->receive() is called I get an exception complaining about the lack of content in my reply. If I remove the line the service does not get a call.

Call to undefined method WebSocket\Server::connect()

Connect method is not on Base class.

Fatal error: Uncaught Error: Call to undefined method WebSocket\Server::connect() in /Applications/XAMPP/xamppfiles/htdocs/cvc/includes/WebSocket/Base.php:48

This is my socket server instance

use WebSocket\Server;

$server = new Server([
	'timeout' => 200,
	'port' => 9000
]);

echo $server->getPort();

while ($server->accept()) {
	try {
		while(1){	
			$message = $server->receive();
			echo "Received $message\n\n";
			$server->send($message, 'text', false);
		}
		
	}
	catch (WebSocket\ConnectionException $e) {
		echo "\n", microtime(true), " Client died: $e\n";
	}
}

WebSocket\ConnectionException: Could not open socket

Hello. I am running this within my Laravel project (server nginx) and here is my issue.
WebSocket\ConnectionException: Could not open socket to "127.0.0.1:8080": Connection refused (111). in /home/forge/project/vendor/textalk/websocket/lib/Client.php:95

and if I change from 127.0.0.1 to 1.0.0.127 I get timeout (110)

Sorry for bad english

PubSub

Hi can I Subscribe and Publish with this class?

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.