Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:06
Show Gist options
  • Save laser/af4d51067816879608fb to your computer and use it in GitHub Desktop.
Save laser/af4d51067816879608fb to your computer and use it in GitHub Desktop.
Socket.IO Chat App
/*
We'll be building a chat application for Seattle-based weather aficionados.
On top of basic chat functionality (sending messages to a chat room, being
notified when users enter/leave the room), the application will provide two
interesting, user-facing features:
1. New users, upon connection to the server, will be sent a private message
containing a summary of the current weather in Seattle.
2. A weather-related fact will be broadcast to the chat room after every 20
messages sent between users.
Behind the scenes, we'll add a few constraints to our server implementation
to make things interesting:
1. The greeting sent to newly-connected users is kept fresh by polling the
National Weather Service every 2 seconds.
2. All messages sent between users containing the string "cloudy" are sent
to an external logging server. This server is notoriously-flaky; in the
event of a failure, we'll retry our POST up to 10 times.
*/
var request = require('request-json'),
io = require('./server');
function log(id, msg, callback) {
function attempt(retries) {
request
.newClient('http://localhost:3000/api/')
.post('log', { id: id, msg: msg }, function(err, response) {
if (!err) callback(err, response);
else {
if (retries < 0) callback(err, response);
else {
setTimeout(function() {
attempt(retries-1);
}, 100);
}
}
});
}
attempt(10);
}
function getWeather(callback) {
request
.newClient('http://localhost:3000/api/')
.get('weather', function(err, response, body) {
callback(err, body.weather[0].main + ', ' + body.main.temp + 'F');
});
}
getWeather(function(err, weather) {
var messageCount = 0;
if (err) throw err
function poll() {
setTimeout(function() {
getWeather(function(err, _weather) {
if (err) throw err;
weather = _weather;
poll()
});
}, 2000);
}
poll();
io.on('connection', function(socket) {
socket.broadcast.emit('message', 'CONN: ' + socket.id);
socket.send('Welcome! Current weather is: ' + weather);
socket.on('message', function(msg) {
io.emit('message', socket.id + ': ' + msg);
if (++messageCount % 20 === 0) {
io.emit('message', 'Did you know...?');
}
if (msg.indexOf("cloudy") !== -1) {
log(socket.id, msg, function(err) {
if (err) throw err;
// otherwise OK
})
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment