A WebSocket server written in PHP.

Overview

WebSocketServer

A WebSocket server written in PHP.

If you like this project gift us a .

Installation.

$ composer require thenlabs/websocket-server 1.0.x-dev

This project has not a stable version yet.

Usage.

In the example directory exists a demo project which implements a bare chat server.

The example/MyChatServer.php file contain the class which, like you can see, implements the logic of the server through an event system.

users[$nickname] = $event->getConnection(); } public function onMessage(MessageEvent $event): void { $senderUser = $event->getConnection(); $senderNick = array_search($senderUser, $this->users); $message = $event->getMessage(); // send the message to the other users. foreach ($this->users as $user) { if ($user !== $senderUser) { $user->send("{$senderNick}: {$message}"); } } } public function onClose(CloseEvent $event): void { $user = $event->getConnection(); $nickname = array_search($user, $this->users); // notify to the other users. foreach ($this->users as $otherUser) { if ($otherUser !== $user) { $otherUser->send("The user {$nickname} has disconnected."); } } unset($this->users[$nickname]); } } ">

// example/MyChatServer.php

use ThenLabs\WebSocketServer\Event\CloseEvent;
use ThenLabs\WebSocketServer\Event\MessageEvent;
use ThenLabs\WebSocketServer\Event\OpenEvent;
use ThenLabs\WebSocketServer\WebSocketServer;

class MyChatServer extends WebSocketServer
{
    protected $users = [];

    public function onOpen(OpenEvent $event): void
    {
        $request = $event->getRequest();
        $nickname = explode('/', $request->getRequestUri())[1];

        // notify to the connected users previously.
        foreach ($this->users as $user) {
            $user->send("User '{$nickname}' has connected.");
        }

        // add the new user to the list.
        $this->users[$nickname] = $event->getConnection();
    }

    public function onMessage(MessageEvent $event): void
    {
        $senderUser = $event->getConnection();
        $senderNick = array_search($senderUser, $this->users);

        $message = $event->getMessage();

        // send the message to the other users.
        foreach ($this->users as $user) {
            if ($user !== $senderUser) {
                $user->send("{$senderNick}: {$message}");
            }
        }
    }

    public function onClose(CloseEvent $event): void
    {
        $user = $event->getConnection();
        $nickname = array_search($user, $this->users);

        // notify to the other users.
        foreach ($this->users as $otherUser) {
            if ($otherUser !== $user) {
                $otherUser->send("The user {$nickname} has disconnected.");
            }
        }

        unset($this->users[$nickname]);
    }
}

The example/start-server.php file contains the script which starts the server.


// example/start-server.php

require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/MyChatServer.php';

$config = [
    'host' => $argv[1] ?? '127.0.0.1',
    'port' => $argv[2] ?? 9090,
];

$server = new MyChatServer($config);
$server->start();

This file should be executed as next:

$ php example/start-server.php

In order to test the example, we can use the example/index.html file which contains three clients which can be used like it's shown next:

Development.

Running the tests.

Start the selenium server.

$ java -jar path/to/selenium-server-standalone-x.y.z.jar

Run PyramidalTests.

$ ./vendor/bin/pyramidal
You might also like...
HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7

HTTP header kit for PHP 7.1+ (incl. PHP 8) based on PSR-7 Installation composer require sunrise/http-header-kit How to use? HTTP Header Collection Mor

PHP Curl ile letgo api kütüphanesi oluşturuldu. php ile letgo giriş yap.

Kendi LETGO API ile işlemler gerçekleştirelim. // email işlemleri $server = 'imap.gmail.com'; $user = '[email protected]'; $pass = 'password'; $port = 9

Guzzle, an extensible PHP HTTP client
Guzzle, an extensible PHP HTTP client

Guzzle, PHP HTTP client Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interf

Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

A Chainable, REST Friendly, PHP HTTP Client. A sane alternative to cURL.

Httpful Httpful is a simple Http Client library for PHP 7.2+. There is an emphasis of readability, simplicity, and flexibility – basically provide the

PHP's lightweight HTTP client

Buzz - Scripted HTTP browser Buzz is a lightweight (1000 lines of code) PHP 7.1 library for issuing HTTP requests. The library includes three clients

HTTPlug, the HTTP client abstraction for PHP

HTTPlug HTTPlug, the HTTP client abstraction for PHP. Intro HTTP client standard built on PSR-7 HTTP messages. The HTTPlug client interface is compati

Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

Unirest in PHP: Simplified, lightweight HTTP client library.

Unirest for PHP Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the

Comments
  • Cambiar la forma de cerrar las conexiones.

    Cambiar la forma de cerrar las conexiones.

    Actualmente se están cerrando las conexiones de la manera: fclose($webSocketConnection->getSocket());. Esto se debe cambiar a $webSocketConnection->close()

    opened by andaniel05 0
Owner
ThenLabs
We make open source software.
ThenLabs
Express.php is a new HTTP - Server especially made for RESTful APIs written in PHP.

express.php Express.php is a new HTTP - Server especially made for RESTful APIs written in PHP. Features Fast The Library is handles requests fast and

null 5 Aug 19, 2022
Read-only WebDAV server written in php8.0; supports browsing archives and GETting files in encodings other than what's on disk

Best Read-only WebDAV Server: TODO Features and notes of implementation Keeping generated files in a place that nginx can find them (2 ways to do this

Joe Koop 1 Nov 17, 2021
Requests - a HTTP library written in PHP, for human beings

Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python library. Requests is ISC Licensed (similar to the new BSD license) and has no dependencies, except for PHP 5.6+.

WordPress 3.5k Jan 6, 2023
LittleProxy is a high performance HTTP proxy written in Java atop Trustin Lee's excellent Netty event-based networking library

LittleProxy is a high performance HTTP proxy written in Java atop Trustin Lee's excellent Netty event-based networking library

null 1.9k Dec 26, 2022
↪️ Bypass for PHP creates a custom HTTP Server to return predefined responses to client requests

Bypass for PHP provides a quick way to create a custom HTTP Server to return predefined responses to client requests.Useful for tests with Pest PHP or PHPUnit.

CiaReis 101 Dec 1, 2022
Transform your WordPress site into a modern GraphQL server: graphql-api.com.

GraphQL API for WordPress Transform your WordPress site into a modern GraphQL server: graphql-api.com. This plugin is the implementation for WordPress

GraphQL API 151 Dec 14, 2022
Server emulator for the Hasbro Em@il Games clients

HasbroPBEMProxy Greg Kennedy, 2021 Server emulator for the Hasbro Em@il Games clients About In 1999 Hasbro launched a series of games under the "Em@il

Greg Kennedy 4 Dec 20, 2022
Event-driven, streaming HTTP client and server implementation for ReactPHP

HTTP Event-driven, streaming HTTP client and server implementation for ReactPHP. This HTTP library provides re-usable implementations for an HTTP clie

ReactPHP 640 Dec 29, 2022
Creating an all in one AI with a web UI to control it. Create your own AI server and/or sell API keys to other people to use your AI.

+ Currently taking an hour or two break to spend some time with the wife. - Then going to work on auto refreshing the chat and document ingestion so y

null 10 Jun 14, 2023
Retrofit implementation in PHP. A REST client for PHP.

Retrofit PHP Retrofit is a type-safe REST client. It is blatantly stolen from square/retrofit and implemented in PHP. ❗ UPGRADE NOTICE ❗ Version 3 int

null 153 Dec 21, 2022