Perhaps I did not fully understand the answers in related questions. I got the long polling ,reverse ajax concept but the thing is this:
My current set up is in my local unit, I am the client and I am the server. I can successfully establish connection to my server and I can send back to my client a message once connection is established, now another scenario comes in, I would just want the server to continuously update my client after establishing the connection. For simplicity purpose, say I would like my client to be updated with the server time so everytime the minute changes, the server sends the most current time to the client(provided that the connection is already established).
I am using node.js and socket.io. The following are my codes:
CLIENT:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Testing</title>
<script src="/socket.io/socket.io.js"></script>
<script language="javascript" type="text/javascript">
var socket = new io.connect("http://127.0.0.1:8080");
socket.on('connect', function(){
// socket.on('news', function (data) {
// socket.emit('my other event', { my: 'data' });
socket.on("test",function(data){
alert(data);
});
socket.onmessage = function (event) {
console.log(event.data);
}
});
console.log(socket);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
SERVER:
var socketOptions = {
transportOptions: {
'xhr-polling': {
closeTimeout: 20000000, //20 mins
timeout: 20000000 //20 mins
}
}
};
var app = require('http').createServer(handler)
, url = require('url')
, io = require('socket.io').listen(app,socketOptions)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
var path = url.parse(req.url).pathname;
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
console.log("ERROR: "+err)
res.writeHead(500);
return res.end('Error loading index.html');
}
// res.writeHead(200);
//res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
res.writeHead(200, {'Content-Type': 'text/html'});
console.log("THIS IS IT");
res.end(data);
});
}
console.log(io);
io.sockets.on('connection', function (socket) {
// socket.send("testing lang kung nagsesend");
// console.log("connection");
// socket.emit('news', { hello: 'world' });
// socket.on('my other event', function (data) {
// console.log(data);
// });
socket.emit("test","Test connection message established,send and received");
});
What do I do with my server codes? I can notice that almost all code samples are in php format.
Create a setInterval with a function in the callback what you want it to do ever set seconds after the connection has been fired. You are looking for something like this:
io.sockets.on('connection', function (socket) {
setInterval(function(){
// do a socket emit here to give data to client
},1000);
}