Last active
August 29, 2015 13:58
-
-
Save baniol/9988752 to your computer and use it in GitHub Desktop.
nodejs, express, socket.io, ejs, basic server
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
var express = require('express'), | |
app = express(), | |
port = 3700, | |
io = require('socket.io').listen(app.listen(port)); | |
app.set('views', __dirname + '/views') | |
// Set plain HTML as our template engine, which requires EJS | |
.engine('html', require('ejs').renderFile) | |
// Ensure that the routes below aren't overwritten by static files | |
.use(app.router) | |
// All our client-side assets will be stored in a public directory | |
.use('/', express.static(__dirname)) | |
/*** Our Routes ***/ | |
.get('/', function(req, res) { | |
res.render('chat.html'); | |
}); | |
// Connection handler, fires whenever someone connects | |
io.sockets.on('connection', function(socket) { | |
// Emit a 'message' to the socket who just connected. | |
socket.emit('message', { | |
message: 'welcome to the chat' | |
}); | |
// "receive" event handler | |
socket.on('receive', function(data) { | |
io.sockets.emit('message', data); | |
}); | |
}); |
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
window.onload = function () { | |
var messages = [], | |
socket = io.connect(window.location.origin), | |
display = document.getElementsByTagName('output')[0], | |
button = document.getElementsByTagName('button')[0], | |
content = document.getElementById('msg'); | |
socket.on('message', function (data) { | |
if (data.message) { | |
messages.push(data.message); | |
var html = ''; | |
for (var i = 0; i < messages.length; i++) { | |
html += messages[i]; | |
} | |
display.innerHTML = html; | |
} else { | |
console.log("There is a problem:", data); | |
} | |
}); | |
button.onclick = function () { | |
socket.emit('receive', {message: content.value}); | |
}; | |
}; |
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<output></output> | |
<div> | |
<label for="msg">Message:</label> | |
<input type="text" id="msg" maxlength="225"> | |
<button>Send Message</button> | |
<script src="/socket.io/socket.io.js"></script> | |
<script src="chat.js"></script> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment