Thứ Bảy, 26 tháng 3, 2016

How To Build Real - Time Chat Application With Laravel


In this tutorial, I will show you how to implement a real-time chat application with Laravel 5 . However , we are not save messages, so we don't need database. 



We will use Laravel 5 for the back-end service, HTML5 and jQuery for a simple front-end application and brain-socket   for real-time communication between the server and clients. 
Lets begin by installing this package through Composer. Edit your Laravel project's composer.json file and add the requirebrainboxlabs/brain-socket:
    "require": {
        ...
        "brainboxlabs/brain-socket": "v1.0.0"
    },
Note: make sure and check packagist.org for updated dependencies but the list above is what has been tested at the time of this writing.
Once the package and all of its dependencies have been installed we need to add the BrainSocketServiceProvider to ourapp/config/app.php file.
Add this line:
'providers' => array(
    ...
    'BrainSocket\BrainSocketServiceProvider',
to the end of the providers array in the config file.
There is also an optional but recommended Facade you should add to the aliases array in the app/config/app.php file.
'aliases' => array(
    ...
    'BrainSocket'     => 'BrainSocket\BrainSocketFacade',
Next open terminal and cd into your Laravel project directory.
run php artisan list and confirm you see the brainsocket: command in the list of commands. It should look like this:
Available commands:
brainsocket
    brainsocket:start
Once you have confirmed the list, run the following command to start the WebSocket server:
php artisan brainsocket:start
Note: The websocket server runs on port 8080 by default. You can change this with the optional --port=port_number on the end of the artisan command.
php artisan brainsocket:start --port=8081
At this point you should see a message in the terminal saying the websocket has been started on the selected port. Terminal will be locked down / unusable at this point, to stop the WebSocket server hit ctrl+c in the terminal.
Note: Any changes to your laravel app / code while the ws server is running are not taken into account. You need to restart the ws server to see any of your changes.
Lets stop the ws server now by hitting ctrl+c in the terminal.
Next in your app/ folder create a file called events.php
Lets add the following code to events.php:
<?php
Event::listen('generic.event',function($client_data){
    return BrainSocket::message('generic.event',array('message'=>'A message from a generic event fired in Laravel!'));
});

Event::listen('app.success',function($client_data){
    return BrainSocket::success(array('There was a Laravel App Success Event!'));
});

Event::listen('app.error',function($client_data){
    return BrainSocket::error(array('There was a Laravel App Error!'));
});
Note: The $client_data parameter passed into the event listener is a POPO (Plain Old PHP Object) with all of the data passed from the client side.
Note: The app.success and app.error events are not required but are helper events for dealing with flash messaging.
Now in app/start/global.php add the following line at the end of the file:
require app_path().'/filters.php';
require app_path().'/events.php';
Great! Now we have a few events to test out on the client side. Run the artisan command php artisan brainsocket:start to start the ws server again.
To make things easier we have created a simple js helper that allows us to interact with our new ws server a bit easier. It's not required but it handles some minor formatting tasks in the background so you don't have to and pairs nicely with our BrainSocket Facade.
Load the script into your app:
<script type="text/javascript" src="js/brain-socket.min.js" />
Create the BrainSocket object:
window.app = {};

app.BrainSocket = new BrainSocket(
        new WebSocket('ws://localhost:8080'),
        new BrainSocketPubSub()
);
The class requires 2 parameters to get up an running:
  • The first is the WebSocket object which should point to a WebSocket server.
  • The second is the BrainSocketPubSub class (you can feel free to implement your own just make sure you pass in an object with the forgetlisten and fire methods).
Note: If you are using our BrainSocket.php package you should see "Connection Established!" messages in the terminal window running your WebSocket server when you load your js app in a browser.
Next we can start subscribing to some custom BrainSocket events via Event.listen.
app.BrainSocket.Event.listen('some.event',function(msg)
{
    console.log(msg);
});

app.BrainSocket.Event.listen('app.success',function(msg)
{
    console.log(msg);
});

app.BrainSocket.Event.listen('app.error',function(msg)
{
    console.log(msg);
});
Note: The msg parameter passed into the event listener is a POJO (Plain Old Javascript Object) that contains client and possibly server objects (also POJOs), which contain the original client data and any server data that was passed back.
Note: The app.success and app.error events are not required but are helper events for dealing with flash messaging.
To fire an event to the WebSocket server you can call:
app.BrainSocket.message('some.event',[some:data]);
Typically you would fire these messages after user interactions take place in your app.
Here's an example with jquery:
$('button.user-signup').click(function(event)
{

    if(something.happens)
    {
        app.BrainSocket.success('Congrats, Welcome to the team!');
    }else
    {
        app.BrainSocket.error('We\'re sorry, there was an error with your submission.');
    }

    return false;

});
And that's it!
Be sure to check out our simple chat app in the example/ directory.

Không có nhận xét nào:

Đăng nhận xét