In the beginning of Web Dev...

Traditional Web Communication

Client

Server

GET /index.html HTTP/1.1
Host: www.example.com
HTTP/1.1 200 OK
Date: Mon, 1 Jan 2015 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 31 Dec 2014 23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Accept-Ranges: bytes
Connection: close

<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World
</body>
</html>

Limitations

  • rigid one-way communication (client to server, server to client)
  • hard to do real-time bidirectional communication between client and server

Socket.IO

Socket.IO

Event-driven

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
  • Detect Events ( Object.on() )
  • Produce Events ( Object.emit() )
  • React to Events

Practise Time

If you're done, try adding these features to your chat app:

  1. Broadcast a message when someone connects or disconnects on client side.
  2. Don't send the message to the user that sent it. Instead, append the message directly as soon as enter is pressed.
  3. Show the number of users online on client side.
  4. Save the messages on server-side and load them on the client side when a user connects.
  5. Auto scroll to bottom as a new message comes in.
Made with Slides.com