从 Web 服务器到客户端 bower 的实时通知

2022-01-06 00:00:00 real-time notifications jquery php

我正在使用 php+mysql 开发约会中心 Web 应用程序.我目前尝试做的是在没有第三方推送器和不使用 jQuery SetInterval AJAX 请求的情况下,在从 Web 服务器向客户端/用户 bowers 进行约会时发送通知.我认为 SetInterval &AJAX 是一种糟糕的方法,因为客户端和服务器之间的流量会过多.

I am developing an appointments center web application using php+mysql. what I currently trying to do is to send notification when an appointment has been made from web server to client/user bowers without third party pushers and without using jQuery SetInterval AJAX request. I think SetInterval & AJAX is a bad approach because there would be too much traffic between the client and the server.

如何在不使用 SetInterval 轮询服务器的情况下实现通知?

How can I implement notifications without polling the server with SetInterval?

推荐答案

您可以使用 NodeJs 做到这一点.NodeJS 是您服务器上的 javascript,可实时将内容推送到连接的客户端.

You can do this using NodeJs. NodeJS is javascript on your server that pushes content to connected clients in real time.

它非常易于使用和设置.您需要一个专用于实时应用的服务器,我使用 http://nodejitsu.com.

Its really easy to use and setup. You need a server dedicated to the real time app, I use http://nodejitsu.com.

服务端

var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, url = require('url')

app.listen(8080);

function handler (req, res) {
// parse URL
var requestURL = url.parse(req.url, true);

// if there is a message, send it
if(requestURL.query.message)
    sendMessage(decodeURI(requestURL.query.message));

// end the response
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("");
}

function sendMessage(message) {
io.sockets.emit('notification', {'message': message});
}

客户端

<script src="socket.io.min.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('notification', function (data) {
    console.log(data.message);
});
</script>

我在下面添加了@intivev 的易于使用的示例,以完成未来读者的答案

I added the easy to use example by @intivev below to complete the answer for future readers

相关文章