Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mobile applications Development - Lecture 17

Mobile applications Development - Lecture 17

Server-Side Programming Primer:
REST
Web Sockets
Server-sent Events

This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).

http://www.di.univaq.it/malavolta

Ivano Malavolta

June 18, 2012
Tweet

More Decks by Ivano Malavolta

Other Decks in Technology

Transcript

  1. REST Main Actors These are the abstractions that make a

    RESTful system: • Resources Resources Resources Resources • Representations Representations Representations Representations • Actions Actions Actions Actions
  2. Resources In general, a RESTful resource is anything that is

    anything that is anything that is anything that is addressable over the Web addressable over the Web addressable over the Web addressable over the Web addressable over the Web addressable over the Web addressable over the Web addressable over the Web Addressable Addressable Addressable Addressable = = = = anything that can be accessed and transferred between clients and servers a resource must have a unique address over the Web Under HTTP these are URIs URIs URIs URIs ex. .../orderinfo?id=123
  3. Representations The representation representation representation representation of resources is what

    is sent back and forth between clients and servers A URL URL URL URL is a specialization of URI that defines the network location of a specific resource es. http://some.domain.com/orderinfo?id=123
  4. Actions Actions are used to operate on resources They make

    up the uniform interface used for client/server data transfers
  5. A Possible Implementation in Java HTTP these are annotated Java

    classes Jersey Resources mySQL Tomcat Connector/J Driver JDBC Jersey
  6. JAX-RS Java API for Java API for Java API for

    Java API for RESTful RESTful RESTful RESTful Web Services Web Services Web Services Web Services It is a Java programming language API that provides support in creating web services according to the REST architectural style Many Implementations Apache CXF Many Implementations Apache CXF Restlet RESTEasy Jersey Wink
  7. Jersey Sun's reference implementation for JAX-RS • Open Source •

    Production Quality Jersey provides the connectors for web services Jersey provides the connectors for web services through Java annotations Java annotations Java annotations Java annotations https://jersey.dev.java.net
  8. Jersey The use of annotations allows us to create Jersey

    resources just as easily as we develop Plain Old resources just as easily as we develop Plain Old Java Objects (POJOs) Jersey manages: • interception of HTTP requests • representation of negotiations • representation of negotiations we can concentrate on the business rules only https://jersey.dev.java.net
  9. Resource A Jersey resource is a plain Java class with

    a @Path annotation annotation Every Jersey resource has a URI pointing to it
  10. HTTP Methods: GET Every HTTP request made to a web

    service is handled by an appropriately annotated method in a resource by an appropriately annotated method in a resource class The name of the method is not important
  11. HTTP Methods: POST The POST request has a payload payload

    payload payload that the framework intercepts and delivers to us in the parameter intercepts and delivers to us in the parameter payload The payload can be a string, but also a binary stream of MIME type image/jpg, so our object type for the payload must change accordingly (InputStream, for instance)
  12. HTTP Methods: PUT Similar to the POST request, the PUT

    request has a payload payload payload payload associated with it, which is stored in the payload payload payload payload associated with it, which is stored in the payload variable * we will see later what @Consumes and @PathParam mean
  13. URI Variables @PathParam gives us access to the value of

    a variable in a URI We have to define also one or more String objects as parameters of the method here, id is just another variable within the scope of the method
  14. Input Formats The @Consumes annotation tells how to receive inbound

    representations from the clients inbound representations from the clients The client sets the Content-Type HTTP header and Jersey The client sets the Content-Type HTTP header and Jersey delegates the request to the corresponding method This annotation works together with @POST and @PUT
  15. Output Formats The @Produces annotation tells how to send outbound

    representations to the clients representations to the clients The client sets the Accept HTTP header that maps The client sets the Accept HTTP header that maps directly to the Content-Type the method produces This annotation works together with @GET, @POST and @PUT
  16. Other Annotations • @FormParams – it lets us read the

    values of name/value pairs passed in as part – it lets us read the values of name/value pairs passed in as part of a POST or PUT request • @HEAD – the method will process HTTP HEAD request • @CookieParam – it is used to extract values from a cookie • @HeaderParam – it is used to extract parameters from an HTTP header • ...
  17. Real-time Web? Polling connect no message connect Browser Server connect

    no message event connect event connect no message http://slidesha.re/LeNohX no message connect no message event connect event http://slidesha.re/LeNohX
  18. Real-time Web? Polling PROs PROs PROs PROs • Easy to

    implement via REST • Easy to implement via REST • Runs on standard HTTP servers CONs CONs CONs CONs • No real-time user experience • Wasted bandwidth • Wasted bandwidth – most requests return no data • High server loads
  19. Real-time Web? Long Polling (Comet) connect Browser Server wait event

    event wait connect wait http://slidesha.re/LeNohX event event connect wait http://slidesha.re/LeNohX
  20. Real-time Web? Long Polling (Comet) PROs PROs PROs PROs •

    Real-time user experience • Real-time user experience CONs CONs CONs CONs • High server loads • High server loads – memory – threads & processes • Still waste of bandwidth
  21. Real-time Web? Server-Sent Events open event stream Server <EventSource> Browser

    event event event event event event onmessage onmessage onmessage http://slidesha.re/LeNohX event onmessage http://slidesha.re/LeNohX
  22. Real-time Web? Long Polling (Comet) PROs PROs PROs PROs •

    Real-time user experience • Real-time user experience CONs CONs CONs CONs • only unidirectional • only unidirectional
  23. Real-time Web? Web Sockets Client/Browser Server GET /text HTTP/1.1 GET

    /text HTTP/1.1 GET /text HTTP/1.1 GET /text HTTP/1.1 Upgrade: WebSocket Upgrade: WebSocket Upgrade: WebSocket Upgrade: WebSocket Connection: Upgrade Connection: Upgrade Connection: Upgrade Connection: Upgrade Host: www.websocket.org ... Host: www.websocket.org ... Host: www.websocket.org ... Host: www.websocket.org ... HTTP/1.1 101 WebSocket Protocol Handshake HTTP/1.1 101 WebSocket Protocol Handshake HTTP/1.1 101 WebSocket Protocol Handshake HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket ... Upgrade: WebSocket ... Upgrade: WebSocket ... Upgrade: WebSocket ... http://slidesha.re/LeNohX TCP comm. TCP comm. TCP comm. TCP comm. channel channel channel channel Full duplex, bidirectional Full duplex, bidirectional Full duplex, bidirectional Full duplex, bidirectional http://slidesha.re/LeNohX
  24. Web Sockets Bidirectional, full Bidirectional, full Bidirectional, full Bidirectional, full-

    - - -duplex communication duplex communication duplex communication duplex communication between devices and server Specifically suited for chat, videogames, drawings sharing, real-time info W3C/IETF standard W3C/IETF standard (http://dev.w3.org/html5/websockets) Requires a Web Socket Server to handle the protocol
  25. Web Sockets • What can be sent into a web

    socket? – UTF8 Strings – UTF8 Strings – Binary Frames it is not a TCP socket (TCP manages only streams of bytes) • WebSockets Protocol prefixes: • WebSockets Protocol prefixes: – ws:// – wss://
  26. Web Sockets Workflow Handshake Handshake Handshake Handshake Upgrade Upgrade Upgrade

    Upgrade Upgrade Upgrade Upgrade Upgrade http://code.google.com/p/websocket-sample/wiki/Tips
  27. Inter-Clients Communication 1. 1. 1. 1. Client notifies Client notifies

    Client notifies Client notifies websocket websocket websocket websocket server server server server of an event, giving ids of recipients recipients 2. The server server server server notifies all the active clients notifies all the active clients notifies all the active clients notifies all the active clients (subscribed to that type of event) 3. 3. 3. 3. Clients process event Clients process event Clients process event Clients process event when given recipient Id matches the client’s one http://bit.ly/Ixcupi
  28. Drawbacks • draft draft draft draft standard • supported by

    latest latest latest latest browsers browsers browsers browsers only • supported by latest latest latest latest browsers browsers browsers browsers only • some proxies proxies proxies proxies may still block WS handshakes • need for keep keep keep keep- - - -alive alive alive alive messages messages messages messages • need to manually manage message message message message queues queues queues queues • every encountered problem results in closing closing closing closing the the the the connection connection connection connection connection connection connection connection you cannot distinguish between: • client or server errors • network errors • timeouts
  29. A Possible Implementation in Java extended Java Servlet HTTP handshake

    Chat Web Socket Chat Web Socket Chat Web Socket Jetty Server Web Socket http://www.eclipse.org/jetty
  30. Server-Sent Events It setups a persistent http connection persistent http

    connection persistent http connection persistent http connection which has to be setup only once which has to be setup only once It is unidirectional unidirectional unidirectional unidirectional: : : : server client SSEs are sent over traditional HTTP SSEs are sent over traditional HTTP SSEs are sent over traditional HTTP SSEs are sent over traditional HTTP it can be easily implemented with standard server- side technologies (eg PHP)
  31. SSE- Overview 1. Client sends a request sends a request

    sends a request sends a request to the server via HTTP 2. The server creates a process, which fetches latest state in 2. The server creates a process, which fetches latest state in the DB and responds back responds back responds back responds back 3. Client gets server response gets server response gets server response gets server response 4. In X seconds client automatically sends next request sends next request sends next request sends next request to the server http://bit.ly/Ixcupi
  32. Client-Side Events You can also listen to customized events (not

    only generic messages generic messages var source = new EventSource(“http://some.url”); var handler = function(event){ console.log(event.data); console.log(event.id); console.log(event.origin); these are all the properties of an console.log(event.origin); console.log(event.lastEventId); } source.addEventListener(‘myEvent', handler, false); properties of an event
  33. Server-Side SSE An SSE is plain text delivered as part

    of a stream from a URL a URL Our data must be treated as a stream
  34. SSE Fields fieldName can be: • data (required) data (required)

    data (required) data (required) – the information to be sent • event event event event – the type of event being sent • id id id id – an identifier for the event to be used when the client – an identifier for the event to be used when the client reconnects • retry retry retry retry – how much time (in milliseconds) should pass before the client tries to reconnect to the URL
  35. Drawbacks • supported by latest latest latest latest browsers browsers

    browsers browsers only • browser browser browser browser discrepancies discrepancies discrepancies discrepancies • browser browser browser browser discrepancies discrepancies discrepancies discrepancies • you need a server that can handle large numbers of large numbers of large numbers of large numbers of simultaneous connections simultaneous connections simultaneous connections simultaneous connections • legacy browsers may drop drop drop drop the HTTP connection the HTTP connection the HTTP connection the HTTP connection after a short timeout
  36. Possible Implementations in Java & PHP Java Servlet start event

    stream keep alives Jetty Server Java Servlet keep alives event stream start event stream Apache Server PHP Page start event stream keep alives event stream