Git Product home page Git Product logo

websockets-1's Introduction

PHP WebSocket server

Build Status Version Downloads License

Simple and multifunctional PHP WebSocket server

ollyxar websockets

Live chat example

chat

Performance

ollyxar websockets performance

Installing WebSockets

The recommended way to install WebSockets is through Composer.

# Install Composer
curl -sS https://getcomposer.org/installer | php

Next, run the Composer command to install the latest stable version of WebSockets:

php composer.phar require ollyxar/websockets

After installing, you need to require Composer's autoloader:

require 'vendor/autoload.php';

Simple WebSocket server

MyHandler.php

use Generator;
use Ollyxar\LaravelAuth\FileAuth;
use Ollyxar\WebSockets\{
    Frame,
    Handler as BaseHandler,
    Dispatcher
};

class MyHandler extends BaseHandler
{
    /**
     * MyHandler constructor.
     * @param $server
     * @param $master
     */
    public function __construct($server, $master)
    {
        parent::__construct($server, $master);
        echo "I'm: #{$this->pid}\n";
    }

    /**
     * @param $client
     * @return Generator
     */
    protected function onConnect($client): Generator
    {
        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => 'User {' . (int)$client . '} Connected.'
        ]))));
    }

    /**
     * @param $clientNumber
     * @return Generator
     */
    protected function onClose($clientNumber): Generator
    {
        yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
            'type'    => 'system',
            'message' => "User {$clientNumber} disconnected."
        ]))));
    }

    /**
     * @param string $message
     * @param int $socketId
     * @return Generator
     */
    protected function onClientMessage(string $message, int $socketId): Generator
    {
        $message = json_decode($message);
        if (!empty($message)) {
            $userName = $message->name;
            $userMessage = $message->message;

            $response = Frame::encode(json_encode([
                'type'    => 'usermsg',
                'name'    => $userName,
                'message' => $userMessage
            ]));

            yield Dispatcher::async($this->broadcast($response));
        }
    }
}

User validation

Base Handler has own method to validate user to be logged in. By default it is always return true. You should provide your own implementation of method to authorize users.

    /**
     * Use this method for custom user validation
     *
     * @param array $headers
     * @param $socket
     * @return bool
     */
    protected function validateClient(array $headers, $socket): bool
    {
        return true;
    }

ws-server.php

/**
 * Lets start our server
 */
(new Server('0.0.0.0', 2083, 6, true))
    ->setCert()
    ->setPassPhrase()
    ->setHandler(MyHandler::class)
    ->run();

Nginx reverse proxy

# choose location path
location /websocket/ {
    # use same host and port from your settings!
    proxy_pass http://0.0.0.0:2082/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 86400;
}

Realtime testing (logging)

The server has internal logger that can output info into console. All that you need is just to enable logging before launching server.

Logger::enable();

output logging

Communicate with server outside the wss protocol

use Ollyxar\WebSockets\Server as WServer;
use Ollyxar\WebSockets\Frame;

$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_connect($socket, WServer::$connector);

$data = new stdClass();
$data->type = 'system';
$data->message = 'hello World!';
$msg = Frame::encode(json_encode($data));

socket_write($socket, $msg);
socket_close($socket);

websockets-1's People

Contributors

alexslipknot avatar koss-shtukert avatar digitalhuman avatar

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.