WebRTC and/or/vs WebSockets

  • #networking #webrtc #websockets
  • 226 words, Read time 1 minute, 8 seconds

So this is kind of a longer version of what I already wrote about why AirHockey ended up using both WebSockets and WebRTC.

WebSockets give you a single, persistent, full-duplex connection between a client and a server. It starts life as an ordinary HTTP request that asks to "upgrade," and once the server agrees, that same socket stays open for both sides to send messages whenever they like. It rides on TCP, which is reliable and ordered by design: every packet is guaranteed to arrive, in sequence, and anything lost gets retransmitted. Lovely for chat and scores. Less lovely for a puck, because one dropped packet holds up everything behind it while you wait on a position update you no longer even care about, which I believe is also called head-of-line blocking.

WebRTC data channels can run over UDP, and more importantly they let you dial the reliability yourself: ordered or unordered, fully reliable or "send it once and move on." For a game you would rather toss a stale paddle position than block on it. It is also peer-to-peer, so once connected the data skips the server and takes the shortest path between two players. The price is the setup pain.

TL;DR: WebSockets when every message must arrive and simplicity matters, WebRTC when speed matters more than guarantees. AirHockey wanted both, so it uses both.