Skip to content

Latest commit

 

History

History
109 lines (72 loc) · 3.14 KB

websockets.md

File metadata and controls

109 lines (72 loc) · 3.14 KB

Websockets

Introduction to Websockets

Why Websockets?

  • Need for bidirectional communication between client and web server
  • HTTP not designed for it
    • Two TCP connections for each client (send/receive)
    • Long Polling
    • High overhead
  • Non-HTTP protocols do not benefit from existing infrastructure
    (e.g. proxies, filtering, authentication)

What are Websockets?

  • Bidirectional communication over ports 80 or 443
  • Handshake
    • Initiated with regular HTTP GET sent by client
    • Server responds with HTTP status code 101 (Switching Protocols)
  • After successful handshake, client and server exchange messages
    • Text
    • Binary
  • Closing handshake closes Websockets connection
  • Browsers have built-in Websockets JavaScript API
  • Many server libraries for Node.js (e.g. Socket.io, ws)

Initial Handshake

Initial Handshake in Chrome Dev Tools

  • Note support for debugging Websockets in browsers' dev tools

Websockets Messages

WS Mesages in Chrome Dev Tools

Programming Websockets

Simple Websockets Server with ws

<!--#include file="websockets/0010-ws-intro/simple-server.ts" -->

Broadcast with ws

<!--#include file="websockets/0010-ws-intro/timer-broadcast.ts" -->

Socket.io Server

<!--#include file="websockets/0020-sio-intro/server.ts" -->

Socket.io HTML

<!--#include file="websockets/0020-sio-intro/public/index.html" -->

Socket.io Client

<!--#include file="websockets/0020-sio-intro/public/main.ts" -->

Further Readings and Exercises