baniol
4/5/2014 - 8:02 AM

nodejs, express, socket.io, ejs, basic server

nodejs, express, socket.io, ejs, basic server

<!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>
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);
  });
});
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});
  };

};