Tạo thông báo realtime với nodejs,express,socketio,laravel

Phần 1:Tạo server nodejs gửi thông báo cho client:
Tạo folder thong_bao_server.Sau đó chạy lệnh sau:

cd thong_bao_server
npm init

Các bạn cứ enter để mặc định.File package.json sẽ có nội dung sau:

{
  "name": "thong_bao_server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Tiếp theo setup webserver:

npm install express ejs socket.io --save

Tiếp theo tạo file index.js với nội dung như sau:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000,function(){
	console.log('server start');
});

app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));

app.get('/', function(req, res){
  res.send('home');
});

io.on("connection", function(socket){
  console.log('Co nguoi ket noi');
  socket.emit('THONG_BAO', 'Xin chào gacoder.info');
});

Phần 2:Client laravel nhận tin nhắn
Sửa file welcome.blade.php thành như sau:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mouse0270-bootstrap-notify/3.1.7/bootstrap-notify.min.js"></script>
    </head>
    <body>
    <h1>Thông báo</h1>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
    <script>
    var socket = io('http://localhost:3000');
    socket.on('THONG_BAO', function(data){
        $.notify({
                message:data 
            },{
                // settings
                delay: 0,
                type: 'danger'
            });
      });

    </script>
    </body>
</html>

Phần 3: Test
Chạy server nodejs

node index.js

Truy cập link laravel.Nếu thấy thông báo như sau là bạn đã thành công

0 Shares

Leave a Reply

avatar
  Subscribe  
Notify of