• Like
  • Save
Asynchronous Web Programming with HTML5 WebSockets and Java
Upcoming SlideShare
Loading in...5
×
 

Asynchronous Web Programming with HTML5 WebSockets and Java

on

  • 8,024 views

(Talk originally given @ KCDC - http://kcdc.info ). ...

(Talk originally given @ KCDC - http://kcdc.info ).
Over the last decade, advances in web computing have removed many of the barriers to entry for developers. New languages, frameworks, and development methodologies have kickstarted new ideas and new ways to develop web applications to make modern life easier and more efficient. WebSockets (introduced as part of HTML5) is one such technology that enables a new class of scalable, super-responsive, collaborative, and real-time web applications with a wide range of uses.

In this talk, we will first cover the basics of asynchronous web programming using WebSockets, including predecessors such as polling and long-polling, applications of WebSockets, its limitations and potential bottlenecks, and potential future improvements.

Next, we will demo and dissect a real-world use case for realtime social data analytics, using the Apache Tomcat implementation of WebSockets and the Java-based Liferay Portal Server. This will include a discussion about development of WebSocket endpoints, its lifecycle within the application container and browser, debugging WebSockets, and scalability topics.

Statistics

Views

Total Views
8,024
Views on SlideShare
7,929
Embed Views
95

Actions

Likes
3
Downloads
3
Comments
0

1 Embed 95

http://speakerrate.com 95

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Asynchronous Web Programming with HTML5 WebSockets and Java Asynchronous Web Programming with HTML5 WebSockets and Java Presentation Transcript

    • Asynchronous WebProgramming with HTML5WebSockets and JavaJames FalknerCommunity Manager, Liferay, Inc.james.falkner@liferay.com@schtool
    • The Asynchronous World
    • The Asynchronous Word• Literally: Without Time• Events that occur outside of the main programexecution flow• Asynchronous != parallel/multi-threading
    • Execution Models
    • Execution ModelsSingle-Threaded Synchronous Model• Not much to say here
    • Execution ModelsThreaded Model• CPU controls interleaving• Developer mustcoordinatethreads/processes• “preemptive multitasking”
    • Execution ModelsAsynchronous Model• Developer controls interleaving• “cooperative multitasking”• Wave goodbye to race conditions,synchronized, and deadlocks!• Windows 3.x, MacOS 9.x, SpaceShuttle
    • Execution ModelsThe green code (your code!)runs uninterrupted until it(you!) reaches a “goodstopping point”(I/O)
    • What does this buy me?NOTHING! Except when• Task Pool is large• Task I/O >> Task CPU• Tasks mostly independent… Like web servers
    • Programming Models
    • Threaded vs. Event-Drivenwhile (true) {client = accept(80);/* blocked! */new Thread(new Handler(client)).start();}vs.new Server(80, {onConnect: {handler.handle(client);}});/* no blocking here, move along */
    • Threaded vs. Event-Driven• Both can solve the exact same set of problems• In fact, they are semantically equivalent• Threaded costs in complexity and contextswitching• Event-Driven costs in complexity and nocontext switching
    • Forces• When to consider event-driven, asynchronousprogramming models?
    • Async/Eventing Support• Hardware/OS: Interrupts, select(), etc• Languages: callbacks, closures, futures,promises, Reactor/IOU pattern• All accomplish the same thing: do this thingfor me, and when you’re done, do this otherdependent thing• Frameworks• Makes async/event programming possible oreasier• JavaEE, Play, Vert.x, Cramp, node.js,Twisted, …
    • Reducing Complexity• Use established patterns• Use established libraries and toolinghttps://github.com/caolan/async
    • Typical Evented Web Apps
    • Event-Driven Java/JavaEE• Java 1.0: Threads and AWT• Java 1.4: NIO (Non-blocking I/O, nee New I/O)• J2EE 1.2: JMS• JavaEE 6: @Asynchronous and CDIJavaEE 7: WebSockets• Future: Lambda Expressions (closures)myButton.addActionListener(ae -> {System.out.println(ae.getSource());});
    • Early Event-Driven Java• Closure-like listeners (e.g. addActionListener(), handlers)• Captured “free” variables must be final• Hogging CPU in listener is bad• References to this and OuterClass.this
    • Event-Driven JavaEE• Servlet 3.0• Async servlets• JAX-RS (Jersey)• Client Async API (via Futures/callbacks)• Server Async HTTP Requests• JMS• Message Redelivery, QoS, scalability, …• CDI/EJB• Via @Inject, @Asynchronous and @Observes
    • JavaEE Example: EventDefinitionpublic class HelloEvent {private String msg;public HelloEvent(String msg) {msg = msg;}public String getMessage() {return message;}}
    • JavaEE Example: EventSubscriber@Statelesspublic class HelloListener {@Asynchronouspublic void listen(@Observes HelloEvent helloEvent){System.out.println("HelloEvent: " + helloEvent);}}
    • JavaEE Example: Event Publish@Named("messenger”)@Statelesspublic class HelloMessenger {@Inject Event<HelloEvent> events;public void hello() {events.fire(new HelloEvent("from bean " +System.currentTimeMillis()));}}<h:commandButtonvalue="Fire!"action="#{messenger.hello}"/>
    • JavaEE Example: Async Servlet
    • JavaEE Example: Async Servlet
    • Event-Driven Framework: Vert.x
    • Event-Driven JavaScript• Not just for the browseranymore• It’s cool to like it! (again)• Language features greatlyaid event-drivenprogramming• Many, many frameworks toaid in better design
    • The Asynchronous Web• Goal: Responsive, Interactive sites• Technique: Push or Pull• First: Pull• Request/Response• AJAX Pull/Poll• Now: Push• Long Polling• Proprietary (e.g. Flash)• Server-Sent Events (nee HTTP Streaming)• WebSockets
    • WebSockets• Bi-directional, full-duplex TCP connection• Asynchronous APIs• Related Standards• Protocol: IETF RFC 6455• Browser API: W3C WebSockets JavaScriptAPI• Client/Server API: JSR-356 (Java)• 50+ Implementations, 15+ Languages• Java, C#, PHP, Python, C/C++, Node, …
    • Wire Protocol
    • Wire Protocol
    • Wire Protocol• FIN• Indicates the last frame of a message• RSV[1-3]• 0, or extension-specific• OPCODE• Frame identifier (continuation, text, close, etc)• MASK• Whether the frame is masked• PAYLOAD LEN• Length of data• PAYLOAD DATA• Extension Data + Application Data
    • WebSockets Options• Endpoint identification• Version negotiation• Protocol Extensions negotiation• Application Sub-protocol negotiation• Security options
    • Handshake
    • Java Server API (JSR-356)• Endpoints represent client/server connection• Sessions model set of interactions overEndpoint• sync/async messages• Injection• Custom encoding/decoding• Configuration options mirror wire protocol• Binary/Text• PathParam• Extensions
    • Java Server API@ServerEndpoint("/websocket")public class MyEndpoint {private Session session;@OnOpenpublic void open(Session session) {this.session = session;}@OnMessagepublic String echoText(String msg) {return msg;}@OnClose…@OnError…public void sendSomething() {session.getAsyncRemote().sendText(“Boo!”);}
    • Client API (JavaScript)var ws = new WebSocket(ws://host:port/endpoint);ws.onmessage = function (event) {console.log(Received text from the server: + event.data);// do something with it};ws.onerror = function(event) {console. log("Uh oh");};ws.onopen = function(event) {// Here we know connection is established,// so enable the UI to start sending!};ws.onclose = function(event) {// Here the connection is closing (e.g. user is leaving page),// so stop sending stuff.};
    • Client API (Other)• Non-Browser APIs for C/C++, Java, .NET, Perl,PHP, Python, C#, and probably othersWebSocket webSocketClient =new WebSocket("ws://127.0.0.1:911/websocket", "basic");webSocketClient.OnClose += new EventHandler(webSocketClient_OnClose);webSocketClient.OnMessage += newEventHandler<MessageEventArgs>(webSocketClient_OnMessage);webSocketClient.Connect());webSocketClient.Send(“HELLO THERE SERVER!”);webSocketClient.Close();
    • Browser Support• Your users don’t care about WebSockets• Fallback support: jQuery, Vaadin, Atmosphere,Socket.IO, Play, etc
    • DemoWebSocketServerEndpointJVMHTTPWS
    • Demo Part DeuxWebSocketServerEndpointJVMNodeHTTPHTTPWS
    • WebSocket Gotchas• Using WebSockets in a thread-based system(e.g. the JVM)• Sending or receiving data before connection isestablished, re-establishing connections• UTF-8 Encoding• Extensions, security, masking make debuggingmore challenging
    • WebSocket Issues• Ephemeral Port Exhaustion• Evolving interfaces• Misbehaving Proxies
    • Acknowledgementshttp://cs.brown.edu/courses/cs168/f12/handouts/async.pdf (Execution Models)http://www.infosecisland.com/blogview/12681-The-WebSocket-Protocol-Past-Travails-To-Be-Avoided.html (problems)http://lucumr.pocoo.org/2012/9/24/websockets-101/ (more problems)http://wmarkito.wordpress.com/2012/07/20/cdi-events-synchronous-x-asynchronous/ (cdi examples)http://blog.arungupta.me/2010/05/totd-139-asynchronous-request-processing-using-servlets-3-0-and-java-ee-6/ (asyncservlets)http://vertx.io (vert.x example)https://cwiki.apache.org/TUSCANYWIKI/develop-websocket-binding-for-apache-tuscany.html (handshake image)http://caniuse.com/websockets (browser compat graph)
    • Asynchronous WebProgramming with HTML5WebSockets and JavaJames FalknerCommunity Manager, Liferay, Inc.james.falkner@liferay.com@schtool