PHP Web Socket server

Related tags

Frameworks phpws
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 Websocket Server that is compatible with socket.io

PHP SocketIO Server PHP Websocket Server that is compatible with socket.io So far the function use in this package is almost same with the naming in s

Cydrick Nonog 7 Dec 21, 2022
An asynchronous event driven PHP socket framework. Supports HTTP, Websocket, SSL and other custom protocols. PHP>=5.3.

Workerman What is it Workerman is an asynchronous event-driven PHP framework with high performance to build fast and scalable network applications. Wo

walkor 10.2k Dec 31, 2022
PHP HI-REL SOCKET TCP/UDP/ICMP/Serial .高可靠性PHP通信&控制框架SOCKET-TCP/UDP/ICMP/硬件Serial-RS232/RS422/RS485 AND MORE!

OHSCE高可靠性的PHP通信框架. Hey!I'm come back! 官方网站:WWW.OHSCE.ORG WWW.OHSCE.COM 最新版本V0.2.0.2 2017-05-10 开发者QQ群:374756165(新2016-09) 捐助: http://www.ohsce.com/ind

null 212 Dec 26, 2022
FreeSWITCH Event Socket Layer library for PHP

FreeSWITCH Event Socket Layer library for PHP Quickstart FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of comple

rtckit 2 May 10, 2022
FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of complex dynamic dialplans/workflows

Asynchronous Event Socket Layer library for PHP Quickstart FreeSWITCH's Event Socket Layer is a TCP control interface enabling the development of comp

rtckit 3 Oct 11, 2022
FrankenPHP is a modern application server for PHP built on top of the Caddy web server

FrankenPHP: Modern App Server for PHP FrankenPHP is a modern application server for PHP built on top of the Caddy web server. FrankenPHP gives superpo

Kévin Dunglas 2.8k Jan 2, 2023
FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Ruby on Rails.

FlyCubePHP FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Rub

Anton 1 Dec 21, 2021
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

appserver.io 951 Dec 25, 2022
Asynchronous server-side framework for network applications implemented in PHP using libevent

phpDaemon https://github.com/kakserpom/phpdaemon Asynchronous framework in PHP. It has a huge number of features. Designed for highload. Each worker i

Vasily Zorin 1.5k Nov 30, 2022
Simple live support server with PHP Swoole Websocket and Telegram API

Telgraf Simple live support server with PHP Swoole Websocket and Telegram API. Usage Server Setup Clone repository with following command. git clone h

Adem Ali Durmuş 6 Dec 30, 2022
Framework for building extensible server-side progressive applications for modern PHP.

Chevere ?? Subscribe to the newsletter to don't miss any update regarding Chevere. Framework for building extensible server-side progressive applicati

Chevere 65 Jan 6, 2023
Simple WebSocket server implemented in PHP.

Bloatless PHP WebSockets Simple WebSocket server implemented in PHP. Installation Requirements Installation procedure Usage Server Applications Timers

bloatless.org 556 Dec 25, 2022
jojo, another http server written in PHP 8.0

جوجو | jojo جوجو، وب‌سروری در ابعاد جوجه برای کارهای کوچک داستان نوشتن جوجو وب‌سروری که تنظیمات مودم TP-link TD-8811 توی اتاقم رو serve میکنه اسمش mic

Amirhossein Baghaie 6 Dec 25, 2022
Socks5 proxy server written in Swoole PHP

php-socks This is a Socks5 proxy server implementation built with PHP & Swoole. To start the proxy server, clone this repo, run composer install to in

Nazmul Alam 3 Jan 23, 2022
💾 High-performance PHP application server, load-balancer and process manager written in Golang. RR2 releases repository.

RoadRunner is an open-source (MIT licensed) high-performance PHP application server, load balancer, and process manager. It supports running as a serv

Spiral Scout 45 Nov 29, 2022
🤯 High-performance PHP application server, load-balancer and process manager written in Golang

RoadRunner is an open-source (MIT licensed) high-performance PHP application server, load balancer, and process manager. It supports running as a serv

Spiral Scout 6.9k Jan 3, 2023
A pocketmine-mp server that we develop live on Twitch every Saturday from 8pm to 10pm (FR)

Server A pocketmine-mp server that we develop live on Twitch every Saturday from 8pm to 10pm (FR) Contributing Pull requests are welcome. For major ch

Gaëtan H 11 Oct 9, 2022
Phpactor Language Server

This package provides a platform for building a Language Server according to the Language Server Specification

Phpactor 27 Dec 24, 2022