PHP Web Socket server

Overview

Important

⛔️ This project is no longer maintained ⛔️

We urge you to look for a replacement.

Description

WebSocket Server and Client library for PHP. Works with the latest HyBi specifications, as well the older Hixie #76 specification used by older Chrome versions and some Flash fallback solutions.

This project was started to bring more interactive features to http://www.u2start.com/

Features

Server

  • Hixie #76 and Hybi #12 protocol versions
  • Flash client support (also serves XML policy file on the same port)
  • Native Firefox, Safari (iPod / iPhone as well), Chrome and IE10 support. With Flash Client every browser supporting Flash works as well (including IE6-9, Opera, Android and other older desktop browsers).
  • Opera (Mobile) supports WebSockets natively but support has been disabled by default. Can be enabled in opera:config.

Client

  • Hybi / Hixie76 support.
  • Event-based Async I/O

Getting started

The easiest way to set up PHPWS is by using it as Composer dependency. Add the following to your composer.json

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/Devristo/phpws"
        }
    ],
    "require": {
        "devristo/phpws": "dev-master"
    }
}

And run php composer.phar install

To verify it is working create a time.php in your project root

require_once("vendor/autoload.php");
use Devristo\Phpws\Server\WebSocketServer;

$loop = \React\EventLoop\Factory::create();

// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);

// Create a WebSocket server using SSL
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);

$loop->addPeriodicTimer(0.5, function() use($server, $logger){
    $time = new DateTime();
    $string = $time->format("Y-m-d H:i:s");
    $logger->notice("Broadcasting time to all clients: $string");
    foreach($server->getConnections() as $client)
        $client->sendString($string);
});


// Bind the server
$server->bind();

// Start the event loop
$loop->run();

And a client time.html as follows

<html>
    <head>
        <title>WebSocket TEST</title>
    </head>
    <body>
        <h1>Server Time</h1>
        <strong id="time"></strong>

        <script>
            var socket = new WebSocket("ws://localhost:12345/");
            socket.onmessage = function(msg) {
                document.getElementById("time").innerText = msg.data;
            };
        </script>
    </body>
</html>

Now run the time.php from the command line and open time.html in your browser. You should see the current time, broadcasted by phpws at regular intervals. If this works you might be interested in more complicated servers in the examples folder.

Getting started with the Phpws Client

The following is a client for the websocket server hosted at http://echo.websocket.org

require_once("vendor/autoload.php");                // Composer autoloader

$loop = \React\EventLoop\Factory::create();

$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);

$client = new \Devristo\Phpws\Client\WebSocket("ws://echo.websocket.org/?encoding=text", $loop, $logger);

$client->on("request", function($headers) use ($logger){
    $logger->notice("Request object created!");
});

$client->on("handshake", function() use ($logger) {
    $logger->notice("Handshake received!");
});

$client->on("connect", function($headers) use ($logger, $client){
    $logger->notice("Connected!");
    $client->send("Hello world!");
});

$client->on("message", function($message) use ($client, $logger){
    $logger->notice("Got message: ".$message->getData());
    $client->close();
});

$client->open();
$loop->run();

Known Issues

  • Lacks ORIGIN checking (can be implemented manually in onConnect using getHeaders(), just disconnect the user when you dont like the Origin header)
  • No support for extension data from the HyBi specs.

Requirements

Server

  • PHP 5.4

  • Open port for the server

  • PHP OpenSSL module to run a server over a encrypted connection

  • http://pecl.php.net/package/pecl_http as its a dependency of Zend\Uri

  • Composer dependencies * These will be installed automatically when using phpws as a composer package.

  • Reactphp

  • ZF2 Logger

Client

  • PHP 5.4
  • Server that implements the HyBi (#8-#12) draft version
  • PHP OpenSSL module to connect using SSL (wss:// uris)
Comments
  • Add close emitter.

    Add close emitter.

    In my application of the WebSocket client, I want to be able to re-open the connection if it has been accidentally closed by the server (lost connection temporarily or something similar). I noticed the stream close emitter is being used, but it's not being forwarded.

    I just added a line that forwards the close emission so that clients can detect when the connection has been closed. #58 references something similar, but I'm not for sure why the issue was closed (or if it has to do with the client implementation).

    opened by sammarks 6
  • Added public function getMessages()

    Added public function getMessages()

    Added the public function getMessages() so that one can test the status of the _messages array without the need to call the readMessage() function (blocking loop).

    Instead of:

    // Wait for an incoming message $msg = $client->readMessage(); // blocking loop

    New usage:

    if($client->getMessages()) // non-blocking ___$msg = $client->readMessage();

    opened by sfranzyshen 6
  • Pull in upstream fix for PHP hostname and SSL when creating new socket

    Pull in upstream fix for PHP hostname and SSL when creating new socket

    PHP 5.6 has a few changes on how SSL is handled; hostnames are now verified during the SSL handshake. This issue was already fixed in react/socket-client here, but the changes didn't cascade since the changed method is overriden in Devristo\Phpws\Client\Connector. This should fix #60 (and maybe other SSL-related bugs).

    opened by sagebind 4
  • Fixed GET header, added Debug functions

    Fixed GET header, added Debug functions

    Basically small fixes, but a setting that needs improvement. I only included it as a "poke the dev"-thing ;). I used this sort of modification to track down the GET issue. I then read on the RFC entry for the WebSocket standarts and figured it expects standart HTTP headers. Well, I know that GET expects a path, not an entire URL. I yet have to figure out how to include a QueryString. But, I think one just appends it to the path... o.o" I have to try and see. I am going to investigate here and use curl -v to do so - it outputs headers too. ^^

    opened by IngwiePhoenix 3
  • Fix for secure connections

    Fix for secure connections

    React\SocketClient\SecureStream does not extend React\Stream\Stream, so this code won't work with secure connections. It should instead look for the interface that both implement.

    opened by alexmace 2
  • fix websocket client reconnection and wss support

    fix websocket client reconnection and wss support

    • Change creation of connector for ReactPHP changes
    • Clean isClosing flag to allow multiple reconnects
    • Default port is now based on protocol (80 or 443)
    opened by linniksa 2
  • Fix for rand parameter

    Fix for rand parameter

    Fix for PHP Warning on 32 bit.

    <?php
    var_dump(pow(255, 4) - 1);
    // float(4228250624)
    
    rand(0, pow(255, 4) - 1);
    // PHP Warning:  rand() expects parameter 2 to be integer, float given
    
    opened by taniko 1
  • Fix for incomplete handshake header

    Fix for incomplete handshake header

    When starting up a Client, the first packet of data received is expected to be a complete header, and no validation of it is performed even for RFC6455 required elements. This addition insures that the entire header has arrived before marking the websocket transport as connected, instead of allowing the late arriving header data to remain in the data stream, resulting in framing synchronization problems and lost data.

    opened by stgnet 1
  • Injection of stream options into websocket client

    Injection of stream options into websocket client

    First of I'd like to say thank you for all your effort you've put into this. I really appreciate it.

    I've had the requirement to authenticate with a client side SSL certificate while connecting to a websocket server. This was not possible in the current master. I've added the possibility to inject stream options into the constructor of the websocket client.

    Additionally, I fixed a small mistake in the README.md: $client->on("connected", ...) => $client->on("connect", ...).

    opened by svengerlach 1
  • Update chat.php

    Update chat.php

    The terminal will show a lot of notices and errors related to an inability to route messages from urls other then /chat. By creating a catchall route we can avoid confusing people.

    opened by DannyWilkerson 1
  • Update chat.php

    Update chat.php

    It was not clear that the example required /chat appended to the connection url. It looks like someone used the echo chat as a boilerplate but did not fully convert the comments.

    opened by DannyWilkerson 1
  • Receive server pong by client ping

    Receive server pong by client ping

    Hello! First of all, tnx for Merged #95

    I want to share my idea of improving the library.

    The best way to check socket status(check server alive) - send clients ping:

    $loop->addPeriodicTimer(mc::socketCheckInterval, function() use($client, $logger){
        $frame = WebSocketFrame::create(WebSocketOpcode::PingFrame);
        $client->sendFrame($frame);
        $logger->notice("ping");
    
        //DO SOMETHING
    });
    
    

    And receive server pong:

    $client->on("pong", function($frame) use ($logger, $client){
        $logger->notice('pong');
    
        //DO SOMETHING
    });
    
    

    Also, it is very important sometimes to look at the server's response:

    $client->on("pong", function($frame) use ($logger, $client){
        $logger->notice('pong');
    
       var_dump($frame->getData());
       var_dump($frame);
    });
    

    Maybe my suggestion needs to be improved or changed, but in the simplest form, PONG is needed

    opened by yura999999999 0
Owner
Chris Tanaskoski
Chris Tanaskoski
PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

Sergey Bykov 63 Feb 14, 2022
Embed live members' count from all your Discord server in your WordPress website

Live Members Counter For Discord This is the repository for the WordPress plugin: Live Members Counter for Discord Live Members Counter For Discord is

null 1 Oct 30, 2021
The very FIRST ever server sided hack client for the PocketMine-MP API (4.x.x)

PHqx or Phqzing Hacks is a Server Sided Hack "Client" you can use for trolling friends (if you have one) or destroying other people at pvp.

Phqzing 5 Jul 25, 2022
A PHP wrapper for Spotify's Web API.

Spotify Web API PHP This is a PHP wrapper for Spotify's Web API. It includes the following: Helper methods for all API endpoints: Information about ar

Jonathan Wilsson 796 Jan 8, 2023
This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via PHP

This library allows you to quickly and easily use the Twilio SendGrid Web API v3 via PHP

Twilio SendGrid 1.4k Dec 27, 2022
playSMS is a web interface for SMS gateways and bulk SMS services

README Latest development release is playSMS version 1.4.4-beta4 Latest stable release is playSMS version 1.4.3 Official project website: https://play

playSMS 662 Dec 31, 2022
Laravel 8.x package wrapper library for Metatrader 5 Web API

Laravel 8.x package wrapper library for Metatrader 5 Web API

Ali A. Dhillon 10 Nov 13, 2022
Laravel Package for 1APP. Learn how to integrate our APIs to build a web or mobile integration to send and accept payments for your application and businesses.

1APP Laravel Library Learn how to integrate our APIs to build a web or mobile integration to accept payments, make payment of Bills and as well custom

O'Bounce Technologies 4 Jul 25, 2022
⚡️ Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC.

Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC. This project is a work-in-progress. Code and docume

Web3 PHP 665 Dec 23, 2022
Lightweight PHP library for WhatsApp API to send the whatsapp messages in PHP provided by ultramsg.com

Ultramsg.com WhatsApp API PHP SDK Lightweight PHP library for WhatsApp API to send the whatsappp messages in PHP provided by Ultramsg.com Installation

Ultramsg 117 Dec 26, 2022
Google-api-php-client - A PHP client library for accessing Google APIs

Google APIs Client Library for PHP Reference Docs https://googleapis.github.io/google-api-php-client/main/ License Apache 2.0 The Google API Client Li

Google APIs 8.4k Dec 30, 2022
Wise-php - This library is written to accommodate the wise API's use in php projects With Wise

Wise-php - This library is written to accommodate the wise API's use in php projects With Wise you can automate payments, connect your business tools, and create ways to manage your finances. You can also power your cross-border and domestic payouts.

Albert Xhani 15 Nov 17, 2022
It's a PHP Application to simplify working with Google Sheets SDK for php.

About GoogleSheetsPHP It's a PHP Application to simplify working with Google Sheets SDK for php. Note: i used Slim 3 to construct the application but

Sami Alateya 5 Dec 20, 2022
Official repository of the AWS SDK for PHP (@awsforphp)

AWS SDK for PHP - Version 3 The AWS SDK for PHP makes it easy for developers to access Amazon Web Services in their PHP code, and build robust applica

Amazon Web Services 5.7k Jan 1, 2023
A framework agnostic PHP library to build chat bots

BotMan If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course. About BotMa

BotMan 5.8k Jan 3, 2023
PHP library for the Stripe API.

Stripe PHP bindings The Stripe PHP library provides convenient access to the Stripe API from applications written in the PHP language. It includes a p

Stripe 3.3k Jan 5, 2023
A simple PHP GitHub API client, Object Oriented, tested and documented.

PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

KNP Labs 2k Jan 7, 2023
A PHP library for communicating with the Twilio REST API and generating TwiML.

twilio-php The default branch name for this repository has been changed to main as of 07/27/2020. Documentation The documentation for the Twilio API c

Twilio 1.4k Jan 2, 2023
Mailgun's Official SDK for PHP

Mailgun PHP client This is the Mailgun PHP SDK. This SDK contains methods for easily interacting with the Mailgun API. Below are examples to get you s

Mailgun Team 1k Dec 23, 2022