Giter Site home page Giter Site logo

php-websocket-client's Introduction

Websocket client for PHP

Use PHP to connect to at websocket service. These 3 methods make the websocket negotiation and connection and handle the hybi10 frame encoding required.

Note : unlike the library ratchetphp/Pawl, this a synchronous library that could be used within blocking kernels like Symfony for example.

Example 1:

try {
   $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',80) );
   $sp->write("hello server");
   echo "Server responded with: " . $sp->read();
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

Example 2, using a session cookie and setting timeout:

try {
    $headers = ["Cookie: SID=".session_id()];
    $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',80,$headers,$errstr,16);
    $bytes_written = $sp->write("hello server");
    $data = $sp->read();
    echo "Server responded with: ". $data;
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

Example 3, using SSL

try {
    $sp = new \Paragi\PhpWebsocket\Client('echo.websocket.org',443,'',$errstr, 10,true) ) {
    $sp->write("hello server");
    echo "Server responded with: " . $sp->read();
} catch (\Paragi\PhpWebsocket\ConnectionException $e) {
   echo "Something gets wrong ".$e->getMessage();
}

Client class

Constructor

Open websocket connection

__construct(string $host [, int $port [, array $additional_headers [, string &error_string [, int $timeout [, resource $context]]]]] )

host A host URL. It can be a domain name like www.example.com or an IP address like local host: 127.0.0.1

port The servers port number

headers (optional) additional HTTP headers to attach to the request. For example to parse a session cookie.

error_string (optional) A referenced variable to store error messages, if any.

timeout (optional) The maximum time in seconds, a read operation will wait for an answer from the server. Default value is 10 seconds.

context (optional) A stream context resource created with stream_context_create() used to set various socket stream options.

write

Send data to server through the websocket, using hybi10 frame encoding.

int write(string $data [,boolean $final])

data Data to transport to server

final (optional) indicate if this block is the final data block of this request. Default true

read

Read data through websocket from the server, using hybi10 frame encoding.

string read([string &error_string])

error_string (optional) A referenced variable to store error messages, i any.

Note:

  • This implementation waits for the final chunk of data, before returning.
  • Reading data while handling/ignoring other kind of packages

Exception

If anything goes wrong (connection, write, read...), a ConnectionException is thrown back. Please catch them all to return a comprehensive message (here's is a sample in a Symfony context) :

try {
    $sp = new \Paragi\PhpWebsocket\Client($this->localIp, $this->wsPort, ['X-Pusher: Symfony']);
    $sp->write($data);
    $reading = $sp->read();
    $ret = "Server responded with: $reading";

    return new JsonResponse(['level' => 'success', 'message' => $ret], Response::HTTP_OK);
} catch (ConnectionException $ex) {
    return new JsonResponse(['level' => 'error', 'message' => $ex->getMessage()], Response::HTTP_SERVICE_UNAVAILABLE);
}

Tests

Tests are running against a local echo server implemented with Ratchet. You'll have to manually start the server in ANOTHER process.

$ php tests/bin/echoserver.php

And now you can launch PhpUnit

$ vendor/bin/phpunit 

Code coverage

With PhpDbg, just launch :

$ phpdbg -qrr vendor/bin/phpunit
$ firefox .coverage/index.html

Contribute

Please let me know if there is any problems with the code. Any contributions are accepted, if the code looks nice, not bloated and otherwise reasonable.

License: MIT: Free

TODO

  • Achieving 100% Code Coverage

php-websocket-client's People

Contributors

cpinkham avatar nabikaz avatar paragi avatar trismegiste avatar tsukasagenesis avatar valkinaz 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

php-websocket-client's Issues

cant connect with wss/::

Hi dear,
I was trying to connect with MEWS socket which host is ''wss://ws.mews-demo.com/ws/connector''. the server must need the keys into cookie. i just added that into headers.
but i am getting the error:

Warning: stream_socket_client(): unable to connect to wss://ws.mews-demo.com/ws/connector:443 (Unable to find the socket transport "wss" - did you forget to enable it when you configured PHP?) in C:\xampp\htdocs\PHP-websocket-client\websocket_client.php on line 101

I need a help badly. Thanks.

my code of example.php

[Question] check connection status

Hi Paragi,
Really good class for PHP. I started using it, however I only use this class to send notifications (one-way) from my server to another websocket server. The only problem I am facing right now is that if for some reason the connection has beed dropped I have to restart my PHP server script because it has to reconnect to the server( websocket) again.
Is there a way to check if connection is alive or it was dropped , so I can reconnect using websocket_open ?

My scenario is:
I open new connection with websocket_open
and then I send notifications using websocket_write

but if in the meantime connection is dropped, my websocket_write function shows ERROR messages that it was unable to send messages? I want to check the connection before writing

send message from php to websocket #145

Hello.

I have a connection created from javascripts successfully towards my websocket server. I send messages and receive the perfect response. I am using the cboden/ratchet library.

Now what I need is to save a message in the database, to be able to send a message from php to the websocket server so that it sends it to the chat. I can't do this.

I've tried the sample code but I can't do anything. Can you guide me a bit?

Thank you.

try {
            $sp = new \Paragi\PhpWebsocket\Client('localhost?idphonenumber=' . $phone->idphonenumber, 9235);
            $sp->write("hello server");
            echo "Server responded with: " . $sp->read();
        } catch (\Paragi\PhpWebsocket\ConnectionException $e) {
            echo "Something gets wrong " . $e->getMessage();
        }

read method mistyped

$payload_len += ord($header needs to be $payload_len += ord($ext in websocket_read

[Question] Is there a way to setup websocket without terminal?

Hi Paragi,

Seems like a really simple websocket client just what I needed, but can I need this to use only to send a notification to the dashboard when clients makes a payment in frontend, so is it possible to run websocket server without terminal for example when the clients starts the session on my site?

Thanks and Regards,
Berat

[Bug] stripos instead of strpos and resolve compare

  1. Must used === false instead of ! for strpos.

Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
ref

  1. I've seen it sometimes return sec-websocket-accept so must be used stripos instead of strpos for case-insensitive

|| !strpos($reaponse_header,'Sec-WebSocket-Accept: ')){

could not connect, syntax error

Parse error: syntax error, unexpected ')' in websocket-client.php on line 85

after manually fix:

Warning: stream_socket_client(): unable to connect to 443 (Failed to parse address "443")

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.