WebSockets

with Socket.io

by Alex LaFroscia

What are WebSockets?

How Does the Internet Work?

  • Your computer asks a server for some data
  • The server sends the data back to your computer
  • This works great for most things, but what about trying to get data in real time?

Enter WebSockets

  • Creates a two-directional connection between your computer and the server
  • Both can react to events taking place on the other

Socket.io

Why Socket.io

  • A standard way to implement the server end of a WebSocket connection
  • Libraries exist for many different types of clients
  • Extremely easy to use
emit
  • The event taking place
  • Sends some data to the other side
  • Can be done from client or server
on
  • Respond to an event taking place
  • Receive data from the other side
  • Can be done from client or server
// Client

// Takes the name of the event and
// the data to be sent as parameters

socket.emit('message', {
    sender: 'Alex LaFroscia',
    body:   'This is the message'
});
// Server

// Takes the name of the event and a
// callback as parameters

socket.on('message', function(data) {
  console.log("Sender: " + data.name);
  console.log("Message: " + data.body);
  // The message from the client gets
  // printed to the server
});

Demo Time

Creating a live chatroom in less than 6 minutes

(maybe)

The Plan

  • Show a list of chat messages on a page
  • Have an input box and send button that allow us to add messages
Made with Slides.com