CS5220 Advanced Topics in Web Programming Introduction to WebSocket Chengyu Sun California State University, Los Angeles
HTML5 JavaScript APIs Canvas, SVG, Media, Web Audio Web Storage, Indexed DB, File Web Worker, Geolocation … Web Socket
The Need for Real-Time, Two-Way Communication for Web App Chat and collaboration Multi-player games Financial applications
The Problem with HTTP Request-Response Model No response unless there’s a request Underlying TCP connection is short-lived (even with the keep-alive header) Good for server/network resource utilization Bad for constant, real-time communication
Workaround (I) Traditional Polling Client periodically sends requests to the server Only good for applications that require infrequent updates, e.g. checking for new emails or breaking news every few minutes
Workaround (II) Long Polling Client sends a request to server, and server does not respond until there’s new information; upon receiving a response, the client immediately sends another request Problems: timeouts, header overhead, latency
Workaround (III) HTTP Streaming Client sends a request to server; the server keeps the response open, and sends back new information as part of the same response Problems Handling of partial response by browser and network intermediaries Additional work to interpret the response stream at the application level
The Solution: Web Socket A protocol upgrade/switch after an initial HTTP handshake Underlying TCP connection remain open Allow sending/receiving text and binary messages Need both client and server support, e.g. IE 10 above and Tomcat 7 or above
Server-Side Java API JSR-356: JavaTM API for WebSocket Dependency: javax.websocket:javax.websocket-api @ServerEndpoint @PathParam Session @OnOpen @OnClose @OnError @OnMessage
Java API Example @ServerEndpoint("/bookings/{guest-id}") public class BookingServer { @OnMessage public void processBookingRequest( @PathParam("guest-id") String guestID, String message, Session session) { ... } } Optional Parameters
Deploy a JSR-356 Application Servlet container scans for all classes annotated with @ServerEndPoint (requires Servlet 3.0 or above)
Example: Simple Chat (Server-Side) A client can join chat at /chat/{name} Store all connections in a static collection Handle lifecycle events Broadcast all messages to all clients One endpoint instance per connection (default endpoint configuration)
Client-Side JavaScript API https://developer.mozilla.org/en-US/docs/Web/API/WebSocket WebSocket(url) ws or wss protocol close() send(data) Binary data may not be supported onopen onclose onerror onmessage MessageEvent
Example: Chat (Client-Side) John: Hello Me: My name is Steve Jane: I’m here too
Further Considerations What if we want additional features like chat rooms, offline messages, administration, etc.? Message format Message routing Message queuing Integration with other application components
From WebSocket to Messaging STOMP, RabbitMQ, SockJS, Spring Integration …