Server-Side Programming Primer
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Server-Side Programming Primer

on

  • 1,403 views

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

Statistics

Views

Total Views
1,403
Views on SlideShare
1,403
Embed Views
0

Actions

Likes
0
Downloads
43
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

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

Server-Side Programming Primer Presentation Transcript

  • 1. Server-Side Programming Primer Ivano Malavolta ivano.malavolta@univaq.it http://www.di.univaq.it/malavolta
  • 2. Roadmap• REST• Web Sockets• Server-sent Events
  • 3. REST (Quick) Refresher In most cases, client-server comunication relies on HTTPhttp://bit.ly/JALve1
  • 4. REST Main ActorsThese are the abstractions that make a RESTful system:• Resources• Representations• Actions
  • 5. ResourcesIn general, a RESTful resource is anything that is addressable over the WebAddressable = 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 URIsex. .../orderinfo?id=123
  • 6. RepresentationsThe representation of resources is what is sent back and forth between clients and serversA URL is a specialization of URI that defines the network location of a specific resourcees. http://some.domain.com/orderinfo?id=123
  • 7. ActionsActions are used to operate on resourcesThey make up the uniform interface used for client/server data transfers
  • 8. A Possible Implementation in Java these are annotated HTTP Java classes Resources Jersey Connector/J Driver JDBC mySQL Tomcat
  • 9. JAX-RS Java API for RESTful Web ServicesIt is a Java programming language API that provides support in creating web services according to the REST architectural style Apache CXFMany Implementations Wink Restlet RESTEasy Jersey
  • 10. Jersey Suns reference implementation for JAX-RS • Open Source • Production Quality Jersey provides the connectors for web services through Java annotationshttps://jersey.dev.java.net
  • 11. Jersey The use of annotations allows us to create Jersey resources just as easily as we develop Plain Old Java Objects (POJOs) Jersey manages: • interception of HTTP requests • representation of negotiations we can concentrate on the business rules onlyhttps://jersey.dev.java.net
  • 12. ResourceA Jersey resource is a plain Java class with a @Path annotationEvery Jersey resource has a URI pointing to it
  • 13. HTTP Methods: GETEvery HTTP request made to a web service is handled by an appropriately annotated method in a resource classThe name of the method is not important
  • 14. HTTP Methods: POSTThe POST request has a payload that the framework intercepts and delivers to us in the parameter payloadThe 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)
  • 15. HTTP Methods: PUTSimilar to the POST request, the PUT request has a payload associated with it, which is stored in the payload variable* we will see later what @Consumes and @PathParam mean
  • 16. HTTP Methods: DELETESimilarly to the other methods...* we will see later what @pathParam means
  • 17. URI Variables@PathParam gives us access to the value of a variable in a URIWe have to define also one or more String objects as parameters of the methodhere, id is just another variable within the scope of the method
  • 18. Input FormatsThe @Consumes annotation tells how to receive inbound representations from the clientsThe client sets the Content-Type HTTP header and Jersey delegates the request to the corresponding methodThis annotation works together with @POST and @PUT
  • 19. Output FormatsThe @Produces annotation tells how to send outbound representations to the clientsThe client sets the Accept HTTP header that maps directly to the Content-Type the method producesThis annotation works together with @GET, @POST and @PUT
  • 20. Other Annotations• @FormParams – 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• ...
  • 21. Employee Directory DEMO
  • 22. Roadmap• REST• Web Sockets• Server-sent Events
  • 23. Real-time Web? Polling Browser connect Server no message connect no message event connect event connecthttp://slidesha.re/LeNohX no message connect no message event connect event
  • 24. Real-time Web? PollingPROs• Easy to implement via REST• Runs on standard HTTP serversCONs• No real-time user experience• Wasted bandwidth – most requests return no data• High server loads
  • 25. Real-time Web? Long Polling (Comet) Browser Server connect wait event event connect waithttp://slidesha.re/LeNohX event event connect wait
  • 26. Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• High server loads – memory – threads & processes• Still waste of bandwidth
  • 27. Real-time Web? Server-Sent Events Browser Server open event stream <EventSource> event event onmessage event event onmessage eventhttp://slidesha.re/LeNohX onmessage event
  • 28. Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• only unidirectional
  • 29. Real-time Web? Web Sockets GET /text HTTP/1.1 Client/Browser Upgrade: WebSocket Server Connection: Upgrade Host: www.websocket.org ... HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket ...http://slidesha.re/LeNohX TCP comm. channel Full duplex, bidirectional
  • 30. Web SocketsBidirectional, full-duplex communication between full- devices and serverSpecifically suited for chat, videogames, drawings sharing, real-time infoW3C/IETF standard (http://dev.w3.org/html5/websockets)Requires a Web Socket Server to handle the protocol
  • 31. Web Sockets• What can be sent into a web socket? – UTF8 Strings – Binary Frames it is not a TCP socket (TCP manages only streams of bytes)• WebSockets Protocol prefixes: – ws:// – wss://
  • 32. Web Sockets Workflow Handshake Upgradehttp://code.google.com/p/websocket-sample/wiki/Tips
  • 33. Inter-Clients Communication 1. Client notifies websocket server of an event, giving ids of recipients 2. The server notifies all the active clients (subscribed to that type of event) 3. Clients process event when given recipient Id matches the client’s onehttp://bit.ly/Ixcupi
  • 34. Web Socket Interfacehttp://www.w3.org/TR/2009/WD-websockets-20091222/
  • 35. Drawbacks• draft standard• supported by latest browsers only• some proxies may still block WS handshakes• need for keep-alive messages keep-• need to manually manage message queues• every encountered problem results in closing the connection you cannot distinguish between: • client or server errors • network errors • timeouts
  • 36. A Possible Implementation in Java extended HTTP handshake Java Servlet Chat Chat Chat Web Socket Web Socket Web Socket Jetty Serverhttp://www.eclipse.org/jetty
  • 37. Chat DEMO
  • 38. Roadmap• REST• Web Sockets• Server-sent Events
  • 39. Server-Sent EventsIt setups a persistent http connectionwhich has to be setup only onceIt is unidirectional: unidirectional:server clientSSEs are sent over traditional HTTP it can be easily implemented with standard server- side technologies (eg PHP)
  • 40. SSE- Overview 1. Client sends a request to the server via HTTP 2. The server creates a process, which fetches latest state in the DB and responds back 3. Client gets server response 4. In X seconds client automatically sends next request to the serverhttp://bit.ly/Ixcupi
  • 41. Client-Side Interfacehttp://dev.w3.org/html5/eventsource/
  • 42. Client-Side EventsYou can also listen to customized events (not only generic messagesvar source = new EventSource(“http://some.url”);var handler = function(event){ console.log(event.data); console.log(event.id); these are all the console.log(event.origin); properties of an console.log(event.lastEventId); event}source.addEventListener(‘myEvent, handler, false);
  • 43. Server-Side SSEAn SSE is plain text delivered as part of a stream from a URLOur data must be treated as a stream
  • 44. Server-Side SSESyntax of an SSE: <fieldName>: <fieldValue>n
  • 45. SSE FieldsfieldName can be:• data (required) – the information to be sent• event – the type of event being sent• id – an identifier for the event to be used when the client reconnects• retry – how much time (in milliseconds) should pass before the client tries to reconnect to the URL
  • 46. Drawbacks• supported by latest browsers only• browser discrepancies• you need a server that can handle large numbers of simultaneous connections• legacy browsers may drop the HTTP connection after a short timeout
  • 47. Possible Implementations in Java & PHP start event stream Java Servlet keep alives event stream Jetty Server start event stream PHP Page keep alives event stream Apache Server
  • 48. CurrentTime DEMO
  • 49. References