Tổng đài tư vấn: 033 688 8648
Hotline: 039 511 6390
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
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