Socket.io - mattoattacko/class GitHub Wiki

WebSockets & Socket.io Overview

WebSockets

  • WebSocket is an communication method that provides a "full-duplex channel" over a single TCP connection.
  • full-duplex channel: refers to the transmission of data in two directions simultaneously. Eg: a telephone (since both users can speak at the same time) but NOT a walkie-talkie (it's half-duplex since only one person can transmit at a time).
  • WebSocket's allow a client and server to talk to each other in real time. Once connected, clients can receive data from the server w/o needing to refresh the website over and over.
  • Works with an event-driven model, allowing both the server and client to react to events and messages.
  • Server streams data to client as it becomes available. Data is pushed to the client from the server, instead of being pulled from the client.
  • Useful for chat, games, etc

Socket.IO

  • Socket.IO is NOT a WebSocket implementation, but the framework behaves like WebSockets.
  • Socket.IO is a real-time engine that works via Node.js events.
  • Node.js events allow us to listen for a connection event, fire up a function when a new user connects to the server, emit a message (probably an event) over a socket.

How Socket.IO works

  • on(): The on() method takes 2 arguments: the name of the event and a callback (eg: "connection"), which will be executed after every connection event.
  • on() is a core Node.js method tied to the EventEmitter class.
  • Connection event returns a socket object that will be passed to the callback function. By using the socket we can send data back to the client in real time.
  • The client listens for the event with the on() method, and then do something with the data contained inside the message/event.
  • Start a React app (via npm start on the CLI). Then wire up the client socket code that will communicate with the server side socket to do things.