VANHIEP.NET - Làm web giá rẻ - Thiết Kế Website - Thiết Kế Ứng Dụng Mobile
Hướng dẫn dựng server socketIO làm thông báo notification cho ứng dụng

Hướng dẫn dựng server socketIO làm thông báo notification cho ứng dụng

I. Chuẩn bị server socket.io 

Bước 1 : Chúng ta cần cài đặt 2 gói thư viện theo lệnh sau

npm install socketio ioredis

Bước 2 : Khởi tạo file server như code sau

const io = require('socket.io')(6001)
console.log('Connected to port 6001')

io.on('error',function(socket){
	console.log('error')
})

io.on('connection',function(socket){
	console.log('Co nguoi vua ket noi'+socket.id)
})

const Redis = require('ioredis')
const redis = new Redis(6379)
redis.psubscribe("*",function(error,count){
	//
  console.log(count);
	
})
redis.on('pmessage',function(partner,channel,message){
	console.log(channel)
	console.log(message)
	console.log(partner)

	message = JSON.parse(message)
	io.emit(channel+":"+message.event,message.data.message)
	console.log('Sent')
})

Bước 3 : Cấu hình server redis để có thể connect remote, sửa file etc/redis.conf theo hướng dẫn trong file, sau khi sửa xong phải khởi động lại dịch vụ web.

II. Cài đặt dự án laravel để push thông báo từ trong môi trường php

Bước 1 : cài đặt gói sau 

composer install predis/predis

Bước 2 : Cấu hình lại file .env và config/database.php

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=125.212.243.160
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_PREFIX=""

Bước 3 : Tạo 1 command và đăng ký nó vào hệ thống laravel

Lệnh tạo command

php artisan make:command Ten_Command

Nội dụng file command

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RedisCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var  string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var  string
     */
    protected $description = 'Subscribe to a Redis channel';

    /**
     * Execute the console command.
     *
     * @return  mixed
     */
    public function handle()
    {
        Redis::subscribe(['test-channel'], function($message) {
            echo $message;
        });
    }
}

Bước 4: Sử dụng

Chỗ nào cần bắn thông báo realtime thì chèn đoạn code này vào

Redis::publish('test-channel', json_encode(['LeeDongChul' => 'vanhiep2008@gmail.com']));

Thay mảng data của bạn vào hàm json_encode