Wednesday, September 23, 2015

Use Web Socket for Chat in Laravel 5 (Using Ratchet for particular user )

Use Web Socket for Chat in Laravel 5 step by step:

If you want to create a chat server for particular user in Laravel 5, then this blog will help you. Its a very easy and fast way to use web socket.

For this firstly you have to install Ratchet package in your application.

Step1:
For this open your composer.json and write this code in "require" key:

"cboden/ratchet": "0.3.*"

Now open open your terminal and go to your root path and run this command

composer update

It will install this package in your application.

Use Web Socket for Chat in Laravel 5


Step2:

Now create a controller and write functions on it , also include the package files.
For this , just go to your terminal and write this command:

php artisan make:controller ChatController


Now go to this file and write the following code on it:

<?php
namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class ChatController implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
        $this->subscriptions = [];
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

Use Web Socket for Chat in Laravel 5

Now you have done all the functionality. Now you'll be in need of create a chat server .

Step3:

For create a chat server , go to your root path and create a file with named php_chat_server.php


write the following code in this file:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

require  'vendor/autoload.php';


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();
?>



Use Web Socket for Chat in Laravel 5

Now you have to create a chat server.
You are done now.

Step4:

Now go to your root path and run this command:

php php_chat_server.php

This will start your chat server .

Step5:

For checking your working code, you have to go to your browser and open your localhost

For test you have to open two browser for this:

Now open your console in both browser and write this:

var conn = new WebSocket('ws://127.0.0.1:8080');

and then press enter

Use Web Socket for Chat in Laravel 5


same like this write the following lines and enter in both browser:

conn.onopen = function(e) {
  console.log("Connection established!");
};



conn.onmessage = function(e) {
  console.log(e.data);
};



conn.send(JSON.stringify({command: "subscribe", channel: "mychannel"}));

Now in only one browser's console write this code

conn.send(JSON.stringify({command: "message", message: "this is message"}));

You'll see this message at 2nd browser.

Use Web Socket for Chat in Laravel 5


You are done.

Thanks

12 comments:

  1. Thanks for this tutorial! It helped me get started with Ratchet in Laravel. Cheers!

    ReplyDelete
  2. Very good tutorial! Thank you!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thanks man very helpful for beginners.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Why if I want save a message using DB for example return in console Fatal Error: Class "X" not found?

    ReplyDelete
  7. But i add:
    Use DB;
    And always return the same

    ReplyDelete
  8. Well, I don't solve this problem, but i can save the message using AJAX when the client send a message, first i active ajax from send message the server from save message, if this return true the message is send a chatController, but i create a chat... and i don't suscribe a new user if this no update the page... so i will try yo use Sessions for suscribe a all users connected.

    I leave these comments to help someone else

    ReplyDelete
  9. it gives me an error when try to run code on chromiun console
    VM78:12 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

    ReplyDelete
  10. Hello,
    it working like a charm! :)
    but i have one question, i do i get the sender user id\name
    when its send the massages?

    there is any way to extends the js websocket event with other information?

    ReplyDelete
  11. Hey, I've tried to add memcached to this chatserver script and im having issues with it, just wondered if you could explain how/why this is failing if you have time. Ive got it connecting to the memcached server but the on message function in the cache controller can no longer use the $cache variable as it is null.

    I've made a question on stack overflow with the code and more info.

    https://stackoverflow.com/questions/46324877/ratchet-server-ioserver-chatcontroller-crashes-wont-work-correctly-with-memcach

    ReplyDelete