Introduction to 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)
- 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)
- Note support for debugging Websockets in browsers' dev tools
- Try it e.g. with Websockets Echo Demo
- Server-side
- Client-side
- Built-in Websockets API
- Use client-side part of server-side library (e.g. Socket.io Client API)
Simple Websockets Server with ws
<!--#include file="websockets/0010-ws-intro/simple-server.ts" -->
- Try it with e.g. Simple Websockets Client
Broadcast with ws
<!--#include file="websockets/0010-ws-intro/timer-broadcast.ts" -->
<!--#include file="websockets/0020-sio-intro/server.ts" -->
<!--#include file="websockets/0020-sio-intro/public/index.html" -->
<!--#include file="websockets/0020-sio-intro/public/main.ts" -->
- Want to know more? Read/watch...
- Exercises