PHP code example of inhere / websocket

1. Go to this page and download the library: Download inhere/websocket library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

inhere / websocket example snippets


use Inhere\WebSocket\WebSocketServer;

$ws = new WebSocketServer();

$ws->on('open', function (WebSocketServer $ws, $data) {
    $ws->send('welcome!');
});

$ws->on(WebSocketServer::ON_MESSAGE, function (WebSocketServer $ws, $data) {
    $ws->send("you input: $data");
});

$ws->start();

use Inhere\WebSocket\Application;
use Inhere\WebSocket\WebSocketServer;

$app = new Application('', 9501);

$app->onOpen(function (WebSocketServer $ws, Application $app, $id) {
    $app->respond([
        'total' => $ws->count()
    ], 'welcome!');
});

$app->onClose(function (WebSocketServer $ws, Application $app) {
    $app->respond([
        'total' => $ws->count()
    ]);
});

$rootHandler = $app->route('/', new \Inhere\WebSocket\handlers\RootHandler());

// commands
$rootHandler->add('test', function ($data, $index, Application $app) {

    return 'hello';
});