doujujian0052 2017-03-09 14:09
浏览 49

实时通知所有连接的客户端PHP Mysql NodeJs Apache

I am developing an application in which i need to send notification to all connected clients in real time. I have used nodejs for real time notification send to connected clients.

Problem is this is working fine on server, While connected clients are not able to display popup notification. While total numbers of notification is increasing as per notification inserted to database on server and clients also. Only problem no popup notification.

code : index.php

<?php
include_once( dirname( __FILE__ ) . '/class/Database.class.php' );
include_once( dirname( __FILE__ ) . '/class/HelperClass.php' );

$pdo = Database::getInstance()->getPdoObject();
$helper = new HelperClass();

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- Meta, title, CSS, favicons, etc. -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>VegFru | Notification</title>

    <!-- Bootstrap core CSS -->

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="fonts/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/animate.min.css" rel="stylesheet">
    <link href="css/pnotify.custom.min.css" rel="stylesheet">

    <!-- Custom styling plus plugins -->
    <link href="css/custom.css" rel="stylesheet">
    <script src="js/jquery.min.js"></script>

</head>


<body class="nav-md">

    <div class="container body">


        <div class="main_container">

            <div class="col-md-3 left_col">
                <div class="left_col scroll-view">

                    <div class="navbar nav_title" style="border: 0;">
                        <a href="index.php" class="site_title"><i class="fa fa-paw"></i> <span>VegFru</span></a>
                    </div>
                    <div class="clearfix"></div>

                    <!-- menu prile quick info -->
                    <div class="profile">
                        <div class="profile_pic">
                            <img src="images/img.jpg" alt="..." class="img-circle profile_img">
                        </div>
                        <div class="profile_info">
                            <span>Welcome,</span>
                            <h2>Ashish Singh</h2>
                        </div>
                    </div>
                    <!-- /menu prile quick info -->

                    <br />

                    <!-- sidebar menu -->
                    <div id="sidebar-menu" class="main_menu_side hidden-print main_menu">

                        <div class="menu_section">
                            <ul class="nav side-menu">
                                <li><a href="#">Push Notification <i class="fa fa-dashboard pull-right"></i></a></li>
                                <li>
                                    <form action="ajax/insertNewMessage.php" id="notification">
                                        <div class="form-group" style="margin-left: 16px; width: 83%">
                                            <input type="checkbox" onclick="client.gerateRandomNotification(this)"/>
                                            <label class="control-label" for="notification-input">Generate Random</label>
                                        </div>
                                        <div class="form-group" style="margin-left: 16px; width: 83%">
                                            <label class="control-label" for="notification-input">Notification Message</label>
                                            <input type="text" id="notification-input" class="form-control" placeholder="Notification Message"><br/>
                                        </div>
                                        <button type="submit" class="btn btn-success" style="margin-left: 16px;">Send Push Notification</button>
                                    </form>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <!-- /sidebar menu -->
                </div>
            </div>
            <!-- top navigation -->
            <div class="top_nav">

                <div class="nav_menu">
                    <nav class="" role="navigation">
<!--                         <div class="nav toggle">
                            <a id="menu_toggle"><i class="fa fa-bars"></i></a>
                        </div>
 -->
                        <ul class="nav navbar-nav navbar-right">
                            <li class="">
                                <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                    <img src="images/img.jpg" alt="">Ashish Singh
                                </a>
                            </li>
                            <li role="presentation" class="dropdown">
                                <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false">
                                    <i class="fa fa-envelope-o"></i>
                                    <span class="badge bg-green"></span>
                                </a>
                            </li>
                            <li role="presentation" class="dropdown">
                                <?php
                                $query = $pdo->prepare( 'SELECT * FROM notification WHERE status = 0 ORDER BY id DESC' );
                                $query->execute();

                                $notifications = $query->fetchAll( PDO::FETCH_OBJ );
                                ?>
                                <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false">
                                    <i class="fa fa-bell-o"></i>
                                    <span class="badge bg-green"><?= count($notifications) > 0 ? count($notifications): '' ?></span>
                                </a>
                                <ul class="dropdown-menu list-unstyled msg_list animated fadeInDown" style="right: -120px !important; border-top-left-radius: 7px; border-top-right-radius: 7px; margin-top: 10px;" role="menu">
                                    <li style="background-color: white">
                                        <div class="text-center">
                                            <a>
                                                <strong><a href="inbox.html">Notification (<?= count($notifications) ?>)</strong>

                                            </a>
                                        </div>
                                    </li>
                                    <div id="notifications-container">
                                        <?php foreach( $notifications as $notification):?>
                                            <li data-id="<?= $notification->id ?>" onclick="client.openNotification(this)">
                                                <a>
                                            <span class="image">
                                        <img src="images/img.jpg" alt="Profile Image" />
                                    </span>
                                            <span>
                                        <span>Ashish Singh</span>
                                            <span class="time"><?php echo $helper->time_elapsed_string($notification->created_at) ?></span>
                                            </span>
                                            <span class="message">
                                         <?php echo $notification->notification ?>
                                    </span>
                                                </a>
                                            </li>
                                        <?php endforeach; ?>

                                    </div>
                                    <li>
                                        <div class="text-center">
                                            <a>
                                                <strong><a href="inbox.html">See All Alerts</strong>
                                                <i class="fa fa-angle-right"></i>
                                            </a>
                                        </div>
                                    </li>
                                </ul>
                            </li>

                        </ul>
                    </nav>
                </div>

            </div>
            <!-- /top navigation -->
        </div>
    </div>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/pnotify.custom.min.js"></script>
    <script src="js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="js/nodeClient.js"></script>
</body>

</html>

nodeserver.js

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );

var app = express();
var server = http.createServer( app );

var io = socket.listen( server );

io.sockets.on( 'connection', function( client ) {
    console.log( "New client" );
    client.on( 'notification', function( data ) {
        console.log( 'Notification received ' + data.notification);
        //client.broadcast.emit( 'message', { name: data.name, message: data.message } );
        io.sockets.emit( 'notification', { notification: data.notification, serverData: data.serverData } );
    });
});

server.listen( 8082 );

nodeclient.js

var client = (function () {
    var socket = io.connect('http://192.168.2.8:8082');
    var interval; //for random notification generation
    function init() {
        buttonClicked();
        socketNotificationUpdate();
    }

    function buttonClicked() {
        $("#notification").on('submit', function (e) {
            e.preventDefault(); //Preventing default submit action

            var $cacheDom = $(this); //Caching the dom so that jQuery doesn't always need to search in the page
            var url = $cacheDom.attr('action'); //Grabbing url of the form
            var notification = $cacheDom.find('div:nth-child(2) input').val();

            $cacheDom.find('div').removeClass('has-error').addClass('has-success').val('');

            if (notification.length == 0) {
                $cacheDom.find('div').removeClass('has-success').addClass('has-error');
                return false;
            }

            //Ajax call to save data
            saveAjaxNotification(notification, url);

        });
    }

    function socketNotificationUpdate() {
        socket.on('notification', function (data) {
            var $cacheDom = $('#notifications-container');
            var actualContent = $cacheDom.html(); //All notification
            var $notificationCount = $cacheDom.parent().prev().find('span'); //Header notification count selector
            var notificationCount = $notificationCount.text(); //Header Notification count

            $notificationCount.text(Number(notificationCount) + 1); //Incrementing after one notification

            var newMsgContent = '<li data-id="' + data.serverData.lastInsertId + '" onclick="client.openNotification(this)"><a><span class="image"><img src="images/img.jpg" alt="Profile Image" /></span><span><span>Ashish Singh</span><span class="time">0 seconds ago</span></span><span class="message">' + data.notification + '</span></a></li>';

            $cacheDom.html(newMsgContent + actualContent);

        });
    }
    function openNotification(that) {
        var notificationId = $(that).attr('data-id');

        $.post('./ajax/readNotification.php', {notification_id: notificationId}, function () {
            $(that).remove(); //removing the clicked notification (optional as it should take the user to new page)
            var $notificationCount = $('#notifications-container').parent().prev().find('span');
            var notificationCount = $notificationCount.text();

            $notificationCount.text(Number(notificationCount) - 1);

            alert('Notification Link will be opened'); //Just for message
            location.href = ""; //Reloading the page as on clicking the notification will take the user to notifications page where all the notification will be shown (read or unread)
        });
    }
    function saveAjaxNotification(notification, url) {
        $.ajax({
            url: url,
            type: "POST",
            data: {notification: notification},
            success: function (data) {
                var serverData = JSON.parse(data);
                socket.emit('notification', {notification: notification, serverData: serverData});
                PNotify.desktop.permission();
                (new PNotify({
                    title: 'Ashish Singh',
                    text: notification,
                    desktop: {
                        desktop: true,
                        icon: 'images/img.jpg'
                    }
                })).get().click(function (e) {
                    if ($('.ui-pnotify-closer, .ui-pnotify-sticker, .ui-pnotify-closer *, .ui-pnotify-sticker *').is(e.target))
                        return;
                    alert('http://vegfru.com/imrealashu/notification/' + serverData.link);
                });
            }
        });
    }
    function gerateRandomNotification(that) {
        var url = $(that).parent().parent().attr('action');
        var count = 1;
        if ($(that).is(':checked')) {
            interval = setInterval(function () {
                saveAjaxNotification('notification' + count, url);
                count++
            }, 3000);

        } else {
            clearInterval(interval);

        }
    }

    init();

    return {
        openNotification: openNotification, //Revealing the openNotification function as it will be used in DOM
        gerateRandomNotification: gerateRandomNotification
    }
})();
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
    • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
    • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)