Skip to content

Instantly share code, notes, and snippets.

@hu2di
Created April 10, 2017 02:49
Show Gist options
  • Save hu2di/143f48dfdd177594f0dc73268b9c49f3 to your computer and use it in GitHub Desktop.
Save hu2di/143f48dfdd177594f0dc73268b9c49f3 to your computer and use it in GitHub Desktop.
Server chat with Node.js and Socket.IO
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//Include .html file
app.get('/', function(req, res) {
//res.send('<h1>Hello World</h1>');
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
//User connected
console.log('a user connected');
//User disconnected
socket.on('disconnect', function() {
console.log('user disconnected');
});
//Show message send from user
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
//Broadcast message to all user
io.emit('chat message', msg);
});
});
//Listen port 3000
http.listen(3000, function() {
console.log('listening on *:3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment