Created
December 7, 2016 19:45
-
-
Save xgqfrms-GitHub/6e1554b5d73f4774dd338dd871611076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// only for Angular2 dist | |
// | |
// # SimpleServer | |
// | |
// A simple chat server using Socket.IO, Express, and Async. | |
// | |
var http = require('http'); | |
var path = require('path'); | |
var async = require('async'); | |
var socketio = require('socket.io'); | |
var express = require('express'); | |
// | |
// ## SimpleServer `SimpleServer(obj)` | |
// | |
// Creates a new instance of SimpleServer with the following options: | |
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_. | |
// | |
var router = express(); | |
var server = http.createServer(router); | |
var io = socketio.listen(server); | |
router.use(express.static(path.resolve(__dirname, 'dist'))); | |
var messages = []; | |
var sockets = []; | |
io.on('connection', function (socket) { | |
messages.forEach(function (data) { | |
socket.emit('message', data); | |
}); | |
sockets.push(socket); | |
socket.on('disconnect', function () { | |
sockets.splice(sockets.indexOf(socket), 1); | |
updateRoster(); | |
}); | |
socket.on('message', function (msg) { | |
var text = String(msg || ''); | |
if (!text) | |
return; | |
socket.get('name', function (err, name) { | |
var data = { | |
name: name, | |
text: text | |
}; | |
broadcast('message', data); | |
messages.push(data); | |
}); | |
}); | |
socket.on('identify', function (name) { | |
socket.set('name', String(name || 'Anonymous'), function (err) { | |
updateRoster(); | |
}); | |
}); | |
}); | |
function updateRoster() { | |
async.map( | |
sockets, | |
function (socket, callback) { | |
socket.get('name', callback); | |
}, | |
function (err, names) { | |
broadcast('roster', names); | |
} | |
); | |
} | |
function broadcast(event, data) { | |
sockets.forEach(function (socket) { | |
socket.emit(event, data); | |
}); | |
} | |
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){ | |
var addr = server.address(); | |
console.log("Chat server listening at", addr.address + ":" + addr.port); | |
}); |
$ npm i -D express async socket.io
$ npm i -D express
$ npm i -D async
$ npm i -D socket.io
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
process.env.PORT || 4200, process.env.IP || "127.0.0.1"
npm packages