Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

php - Real time notification from web server to client bowers

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Server Side

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});
}

Client Side

<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>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...