Skip to content

Instantly share code, notes, and snippets.

@gin1314
Created July 2, 2013 13:09
Show Gist options
  • Save gin1314/5909166 to your computer and use it in GitHub Desktop.
Save gin1314/5909166 to your computer and use it in GitHub Desktop.
js: ajax & nodejs long polling
// Client.js
var Socket = function(ip, port, name) {
this.ip = ip;
this.port = port;
this.name = name;
this._cbs = [];
this._poll();
};
// Call the server periodically for data.
Socket.prototype._poll = function() {
var that = this;
// if the server does not return then call it again
var timer = setTimeout(function() {
this._poll();
}, 5000);
$.ajax({
type: "GET",
timeout: 5000,
data: {
name: this.name
},
url: this.ip + ":" + this.port,
success: function(data) {
// server returned, kill the timer.
clearTimeout(timer);
// send the message to the callback.
for (var i = 0; i < that._cbs.length; i++) {
that._cbs[i](data);
}
// call the server again
that._poll();
}
});
};
// Add a callback for a message event
Socket.prototype.on = function(event, cb) {
if (event === "message") {
this._cbs.push(cb);
}
};
// Send a message to the server
Socket.prototype.send = function(message) {
$.ajax({
data: {
message: message,
name: this.name
},
type: "GET",
url: this.ip + ":" + this.port
});
};
var socket = new Socket('192.168.1.1', '8081', "Raynos");
socket.on("message", function(data) {
console.log(data);
});
socket.send("Hello world!");
// server.js
var url = require("url");
var events = require("events");
// store messages for clients
var clients = {};
var emitter = new events.EventEmitter();
http.createServer(function(req, res) {
// get query string data
var data = url.parse(req.url, true).query;
// if client is not initialized then initialize it.
if (data.name && !clients[data.name]) {
clients[data.name] = [];
}
// if you posted a message then add it to all arrays
if (data.message) {
for (var k in clients) {
clients[k].push(data.name + " : " + data.message);
}
// tell long pollers to flush new data.
emitter.emit("new-data");
} else if (clients[data.name].length > 0) {
// else empty the clients array down the stream
for (var i = 0; i < clients[data.name].length; i++) {
res.write(clients[data.name].shift());
};
res.end();
// long polling magic.
} else {
var cb = function() {
for (var i = 0; i < clients[data.name].length; i++) {
res.write(clients[data.name].shift());
};
res.end();
// kill that timer for the response timing out.
clearTimeout(timer);
}
// when we get data flush it to client
emitter.once("new-data", cb);
var timer = setTimeout(function() {
// too long has passed so remove listener and end response.
emitter.removeListener(cb);
res.end();
}, 4500);
}
}).listen(8081);
@wanming
Copy link

wanming commented Sep 16, 2016

同时发过来两个请求的话,这个 emitter 是不是会搞混=。=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment