All Projects → arthurkushman → Php Wss

arthurkushman / Php Wss

Licence: mit
Web-socket server/client with multi-process and parse templates support on server and send/receive options on client

Projects that are alternatives of or similar to Php Wss

Websockets
Library for building WebSocket servers and clients in Python
Stars: ✭ 3,724 (+3082.91%)
Mutual labels:  websocket, websockets, websocket-server, websocket-client
Arduinowebsockets
arduinoWebSockets
Stars: ✭ 1,265 (+981.2%)
Mutual labels:  websocket, websockets, websocket-server, websocket-client
Beast
HTTP and WebSocket built on Boost.Asio in C++11
Stars: ✭ 3,241 (+2670.09%)
Mutual labels:  websocket, websockets, websocket-server, websocket-client
Awesome Websockets
A curated list of Websocket libraries and resources.
Stars: ✭ 850 (+626.5%)
Mutual labels:  websocket, websockets, websocket-server, websocket-client
Microwebsrv2
The last Micro Web Server for IoTs (MicroPython) or large servers (CPython), that supports WebSockets, routes, template engine and with really optimized architecture (mem allocations, async I/Os). Ready for ESP32, STM32 on Pyboard, Pycom's chipsets (WiPy, LoPy, ...). Robust, efficient and documented!
Stars: ✭ 295 (+152.14%)
Mutual labels:  websocket, websockets, websocket-server, routes
Websocket
A PHP implementation of WebSocket.
Stars: ✭ 54 (-53.85%)
Mutual labels:  websocket, websocket-server, websocket-client
Websocket
The Hoa\Websocket library.
Stars: ✭ 421 (+259.83%)
Mutual labels:  websocket, websocket-server, websocket-client
Ulfius
Web Framework to build REST APIs, Webservices or any HTTP endpoint in C language. Can stream large amount of data, integrate JSON data with Jansson, and create websocket services
Stars: ✭ 666 (+469.23%)
Mutual labels:  websockets, websocket-server, websocket-client
Deno Websocket
🦕 A simple WebSocket library like ws of node.js library for deno
Stars: ✭ 74 (-36.75%)
Mutual labels:  websocket, websocket-server, websocket-client
Python Slack Sdk
Slack Developer Kit for Python
Stars: ✭ 3,307 (+2726.5%)
Mutual labels:  websocket, websockets, websocket-client
Gun
HTTP/1.1, HTTP/2 and Websocket client for Erlang/OTP.
Stars: ✭ 710 (+506.84%)
Mutual labels:  websocket, websockets, websocket-client
Starscream
Websockets in swift for iOS and OSX
Stars: ✭ 7,105 (+5972.65%)
Mutual labels:  websocket, websockets, websocket-client
Microwebsrv
A micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (used on Pycom modules & ESP32)
Stars: ✭ 420 (+258.97%)
Mutual labels:  websocket, websockets, websocket-server
Java Slack Sdk
Slack Developer Kit (including Bolt for Java) for any JVM language
Stars: ✭ 393 (+235.9%)
Mutual labels:  websocket, websockets, websocket-client
Autobahn Testsuite
Autobahn WebSocket protocol testsuite
Stars: ✭ 603 (+415.38%)
Mutual labels:  websocket, websocket-server, websocket-client
Sandstone
PHP microframework designed to build a RestApi working together with a websocket server. Build a real time RestApi!
Stars: ✭ 98 (-16.24%)
Mutual labels:  websocket, websockets, websocket-server
Cowboy
Small, fast, modern HTTP server for Erlang/OTP.
Stars: ✭ 6,533 (+5483.76%)
Mutual labels:  websocket, websockets, websocket-server
Jiny
Lightweight, modern, simple JVM web framework for rapid development in the API era
Stars: ✭ 40 (-65.81%)
Mutual labels:  websocket, websocket-server, websocket-client
Websocket Client
🔧 .NET/C# websocket client library
Stars: ✭ 297 (+153.85%)
Mutual labels:  websocket, websockets, websocket-client
Oatpp Websocket
oatpp-websocket submodule.
Stars: ✭ 26 (-77.78%)
Mutual labels:  websocket, websocket-server, websocket-client

php-wss

Web-socket server/client with multi-process and parse templates support on server and send/receive options on client

Scrutinizer Code Quality Build Status Latest Stable Version Total Downloads License: MIT

Library comes with several main options

Server:

  • it`s a web-socket server for multiple connections with decoding/encoding for all events out of the box (with Dependency Injected MessageHandler)
  • it has GET uri parser, so you can easily use any templates
  • multiple process per user connections support, so you can fork processes to speed up performance deciding how many client-connections should be there
  • broadcasting message(s) to all clients
  • origin check
  • ssl server run

Client:

  • You have the ability to handshake (which is performed automatically) and send messages to server
  • Receive a response from the server
  • Initiate connection via proxy

How do I get set up?

Preferred way to install is with Composer.

perform command in shell

 composer require arthurkushman/php-wss

OR

just add

"require": {
  "arthurkushman/php-wss": ">=1.3"
}

to your projects composer.json.

Implement your WebSocket handler class - ex.:

<?php
use WSSC\Contracts\ConnectionContract;
use WSSC\Contracts\WebSocket;
use WSSC\Exceptions\WebSocketException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class ServerHandler extends WebSocket
{

    /*
     *  if You need to parse URI context like /messanger/chat/JKN324jn4213
     *  You can do so by placing URI parts into an array - $pathParams, when Socket will receive a connection
     *  this variable will be appropriately set to key => value pairs, ex.: ':context' => 'chat'
     *  Otherwise leave $pathParams as an empty array
     */

    public $pathParams = [':entity', ':context', ':token'];
    private $clients = [];

    private $log;

    /**
     * ServerHandler constructor.
     *
     * @throws \Exception
     */
    public function __construct()
    {
        // create a log channel
        $this->log = new Logger('ServerSocket');
        $this->log->pushHandler(new StreamHandler('./tests/tests.log'));
    }

    public function onOpen(ConnectionContract $conn)
    {
        $this->clients[$conn->getUniqueSocketId()] = $conn;
        $this->log->debug('Connection opend, total clients: ' . count($this->clients));
    }

    public function onMessage(ConnectionContract $recv, $msg)
    {
        $this->log->debug('Received message:  ' . $msg);
        $recv->send($msg);
    }

    public function onClose(ConnectionContract $conn)
    {
        unset($this->clients[$conn->getUniqueSocketId()]);
        $this->log->debug('close: ' . print_r($this->clients, 1));
        $conn->close();
    }

    /**
     * @param ConnectionContract $conn
     * @param WebSocketException $ex
     */
    public function onError(ConnectionContract $conn, WebSocketException $ex)
    {
        echo 'Error occured: ' . $ex->printStack();
    }

    /**
     * You may want to implement these methods to bring ping/pong events
     *
     * @param ConnectionContract $conn
     * @param string $msg
     */
    public function onPing(ConnectionContract $conn, $msg)
    {
        // TODO: Implement onPing() method.
    }

    /**
     * @param ConnectionContract $conn
     * @param $msg
     * @return mixed
     */
    public function onPong(ConnectionContract $conn, $msg)
    {
        // TODO: Implement onPong() method.
    }
}

To save clients with their unique ids - use getUniqueSocketId() which returns (type-casted to int) socketConnection resource id.

Then put code bellow to Your CLI/Console script and run

<?php
use WSSC\WebSocketServer;
use WSSCTEST\ServerHandler;
use WSSC\Components\ServerConfig;

$config = new ServerConfig();
$config->setClientsPerFork(2500);
$config->setStreamSelectTimeout(2 * 3600);

$webSocketServer = new WebSocketServer(new ServerHandler(), $config);
$webSocketServer->run();

How do I set WebSocket Client connection?

<?php
use WSSC\WebSocketClient;
use \WSSC\Components\ClientConfig;

$client = new WebSocketClient('ws://localhost:8000/notifications/messanger/yourtoken123', new ClientConfig());
$client->send('{"user_id" : 123}');
echo $client->receive();

That`s it, client is just sending any text content (message) to the Server.

Server reads all the messages and push them to Handler class, for further custom processing.

How to pass an optional timeout, headers, fragment size etc?

You can pass optional configuration to WebSocketClient's constructor e.g.:

<?php
use WSSC\WebSocketClient;
use WSSC\Components\ClientConfig;

$config = new ClientConfig();
$config->setFragmentSize(8096);
$config->setTimeout(15);
$config->setHeaders([
    'X-Custom-Header' => 'Foo Bar Baz',
]);

// if proxy settings is of need
$config->setProxy('127.0.0.1', '80');
$config->setProxyAuth('proxyUser', 'proxyPass');

$client = new WebSocketClient('ws://localhost:8000/notifications/messanger/yourtoken123', $config);

If it is of need to send ssl requests just set wss scheme to constructors url param of WebSocketClient - it will be passed and used as ssl automatically.

You can also set particular context options for stream_context_create to provide them to stream_socket_client, for instance:

$config = new ClientConfig();
$config->setContextOptions(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]);

or any other available options see - https://www.php.net/manual/en/context.php.

BroadCasting

You may wish to broadcast messages by simply calling broadCast method on Connection object in any method of your ServerHandler class:

$conn->broadCast('hey everybody...');

// or to send multiple messages with 2 sec delay between them
$conn->broadCastMany(['Hello', 'how are you today?', 'have a nice day'], 2);

Origin check

To let server check the Origin header with n hosts provided:

$config = new ServerConfig();
$config->setOrigins(["example.com", "otherexample.com"]);
$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();

Server will automatically check those hosts proceeding to listen for other connections even if some failed to pass check.

SSL Server run options

use WSSC\Components\ServerConfig;
use WSSC\WebSocketServer;

$config = new ServerConfig();
$config->setIsSsl(true)->setAllowSelfSigned(true)
    ->setCryptoType(STREAM_CRYPTO_METHOD_SSLv23_SERVER)
    ->setLocalCert("./tests/certs/cert.pem")->setLocalPk("./tests/certs/key.pem")
    ->setPort(8888);

$websocketServer = new WebSocketServer(new ServerHandler(), $config);
$websocketServer->run();

How to test

To run the Server - execute from the root of a project:

phpunit --bootstrap ./tests/_bootstrap.php ./tests/WebSocketServerTest.php

To run the Client - execute in another console:

phpunit --bootstrap ./tests/_bootstrap.php ./tests/WebSocketClientTest.php

PHP7 support since version 1.3 - with types, returns and better function implementations.

PS U'll see the processes increase named "php-wss" as CPP (Connections Per-Process) will grow and decrease while stack will lessen. For instance, if set 100 CPP and there are 128 connections - You will be able to see 2 "php-wss" processes with for ex.: ps aux | grep php-wss

Used by:

alt Avito logo

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].