consik / yii2-websocket

Yii2 websocket server component
MIT License
92 stars 34 forks source link

Need more detailed examples. #15

Open hassanuos opened 5 years ago

hassanuos commented 5 years ago

Hi, Its great package for the new peoples who use this. Sir, could you please extend this chat example with multiple scenarios it will helpful for new peoples. And it's a request if you consider, please.

hassanuos commented 5 years ago

I need to get the online users list.

StackOverflow

public function commandSubscribe(ConnectionInterface $client, $msg)
{   
    $request = @json_decode($msg, true);
    $client->talkId = $request['talk_id'] ?? null;
    $client->userId = $request['user_id'] ?? null;
    foreach ($this->clients as $key=>$chatClient) {
         $onlineUsers[] = $chatClient->name;
    }
    $client->send( json_encode(['onlineUsers'=> $onlineUsers, 'room'=>$client->talkId, 'user' =>$client->userId ,'message'=> 'User added to room']) );
}

Response:{"onlineUsers":{},"room":"provider","user":"hassan","message":"User added to room"}

Any solution to this issue. Thanks in advance.

i-internet commented 3 years ago
<?php
namespace app\commands;

use consik\yii2websocket\events\WSClientEvent;
use yii\console\Controller;
use consik\yii2websocket\events\WSClientMessageEvent;
use consik\yii2websocket\WebSocketServer;
use Ratchet\ConnectionInterface;
/*
 *
 * Starting yii2 console application as daemon using nohup
 * nohup php yii _ControllerName_/_ActionName_ &
 *
 * */
class WebSocketServerController extends Controller
{
    public function actionStart($port = null)
    {
        $server = new EchoServer();
        if ($port) {
            $server->port = $port;
        }
        $server->on(WebSocketServer::EVENT_WEBSOCKET_OPEN, function($e) use($server) {
            echo "Server started at port " . $server->port;
        });
        $server->on(WebSocketServer::EVENT_CLIENT_MESSAGE, function($e) use($server) {
            echo PHP_EOL;    echo PHP_EOL;
            echo "New client message " . $e->message;
        });

        $server->start();

    }
}

class EchoServer extends WebSocketServer
{

    public function init()
    {
        parent::init();

        $this->on(self::EVENT_CLIENT_MESSAGE, function (WSClientMessageEvent $e) {
            $e->client->send($e->message);
        });
        $this->on(self::EVENT_CLIENT_CONNECTED, function(WSClientEvent $e) {
            $e->client->name = null;
        });
    }

    /**
     * override method getCommand( ... )
     *
     * For example, we think that all user's message is a command
     */
    protected function getCommand(ConnectionInterface $from, $msg)
    {
        $request = json_decode($msg, true);
        return !empty($request['action']) ? $request['action'] : parent::getCommand($from, $msg);
    }

    public function commandChat(ConnectionInterface $client, $msg)
    {
        $request = json_decode($msg, true);
        $result = ['message' => ''];

        if (!$client->name) {
            $result['message'] = 'Set your name';
        } elseif (!empty($request['message']) && $message = trim($request['message']) ) {
            foreach ($this->clients as $chatClient) {
                $chatClient->send( json_encode([
                    'type' => 'chat',
                    'from' => $client->name,
                    'message' => $message
                ]) );
            }
        } else {
            $result['message'] = 'Enter message';
        }

        $client->send( json_encode($result) );
    }

    public function commandSetName(ConnectionInterface $client, $msg)
    {
        $request = json_decode($msg, true);
        $result = ['message' => 'Username updated'];

        if (!empty($request['name']) && $name = trim($request['name'])) {
            $usernameFree = true;
            foreach ($this->clients as $chatClient) {
                if ($chatClient != $client && $chatClient->name == $name) {
                    $result['message'] = 'This name is used by other user';
                    $usernameFree = false;
                    break;
                }
            }
            if ($usernameFree) {
                $client->name = $name;
            }
        } else {
            $result['message'] = 'Invalid username';
        }
        $client->send(json_encode($result) );
    }

    /**
     * Implement command's method using "command" as prefix for method name
     *
     * method for user's command "ping"
     */
    function commandPing(ConnectionInterface $client, $msg)
    {
        $client->send('Pong');
    }

}