Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Many of the comments and logic in this and associated files are inspired by or copied from socket.io/get-started/chat/ and more from their website.
- var app = require('express')();
- var http = require('http').Server(app);
- // The main idea behind Socket.IO is that you can send and receive any events you want, with any data you want. Any objects that can be encoded as JSON will do, and binary data is supported too.
- // Notice that I initialize a new instance of socket.io by passing the http (the HTTP server) object
- var io = require('socket.io')(http);
- var filesys = require('fs');
- // sets nL to system specific newline character. In Unix like systems it's "\n" but in Windows it's "\n\r".
- var nL = require('os').EOL;
- // when there is an http request to specified path (/), the res object gets sent as http response.
- app.get('/', function(req, res){
- res.sendFile(__dirname + '/index.html');
- });
- var port = 3000;
- http.listen(port, function(){
- console.log('listening on ' + port.toString());
- });
- // Event listener, runs function on connnection
- io.on('connection', function(socket){
- io.emit('chat message', 'a user connected');
- filesys.appendFile(__dirname + '/log/log.txt', 'a user connected' + nL, function(err) {
- if (err) throw err;
- });
- console.log('a user connected');
- socket.on('disconnect', function (){
- io.emit('chat message', 'a user disconnected');
- console.log('a user disconnected');
- filesys.appendFile(__dirname + '/log/log.txt', 'a user disconnected' + nL, function(err) {
- if (err) throw err;
- });
- });
- socket.on('chat message', function(msg) {
- io.emit('chat message', msg);
- console.log('message: ' + msg);
- filesys.appendFile(__dirname + '/log/log.txt', 'A user says: ' + msg + nL, function(err) {
- if (err) throw err;
- });
- });
- //do something when app is closing
- // catch ctrl+c event and exit normally
- process.on('SIGINT', function (code) {
- io.emit("chat message", "Server CLOSED");
- console.log("Server Closed");
- process.exit(2);
- });
- //catches uncaught exceptions
- process.on('uncaughtException', function(ev) {io.emit('chat message', 'Warning: server crashed')});
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement