Real-Time Chat App An intro to HTML5 Websockets and node.js GeekCamp SG 2013 by @joshzteng Sunday, September 8, 13
How The Web Works HTTP Request eg. get / from Client google.com Server Browser HTTP Response header body etc.
So Based on this knowledge how would we naively build a real-time app? Client (user) sends message (HTTP Request) Server receives message and stores it Server response with a success message - HTTP status code: 200 (HTTP Respond) Other clients (users) request for new messages continuously (HTTP Request) Server sends new message (HTTP Respond)
I’m Kay. Send my message: “How’s it going?” Client Server Browser I receive your request, kay Any new message? Yes! Here it is “How’s it going” from Kay Client Client Browser Browser Client Client Browser Browser Client PROBLEM Browser Every client constantly ask for new messages. (every second?). the client has to initiate the request.
Question When should clients request for new messages? Client has no idea when the server receives a new message In previous example we solved it by: Client request for new messages on fixed regular intervals Crazy number of request. Imagine 100 chat clients requesting new messages every second. That’s 100 x 60 = 6000 requests and responses per minute! imagine u hv 5 kids at the back of your car, n each and every one of them asking you are we there yet, are we there yet are we there yet.. n u hv to reply no, we’re not there yet. no, we’re not there yet for 5 times car back seat analogy
What’s the deal with the headers? 871 bytes of unnecessary information per request cycle! Doesn’t seem like much. Imagine 1000 clients polling every second! Network throughput is (871 x 1000) = 871, 000 bytes! or 6.6 Mbps! How about 10,000 or 100,000 clients/ users? (66Mbps! 665 Mbps!) Doesn’t even include data yet! Siao! Super unnecessary for a chat app! car back seat analogy
That was a technique called polling Sounds very stupid but this wasn’t that uncommon in the not-so- distant past
Other alternatives Long polling HTTP Streaming etc meh..
What is WebSocket? HTML5 Specification Communication protocol enables browsers to have bi-directional communication with a server over a single channel Server can push/broadcasts messages to clients without client initiating a new request Native mobile app can be a client too!
WebSocket “reducing kilobytes of data to 2 bytes. and reducing latency from 150ms to 50ms far more than marginal In fact these 2 factors alone are enough to make WebSocket seriously interesting..”
Use Case Real-time apps chat stock ticker news report traffic patterns real-time games? etc..