Server-Side Programming Primer


Published on

Mobile applications Development - Lecture 17
Server-Side Programming Primer:
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).

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Server-Side Programming Primer

  1. 1. Server-Side Programming Primer Ivano Malavolta
  2. 2. Roadmap• REST• Web Sockets• Server-sent Events
  3. 3. REST (Quick) Refresher In most cases, client-server comunication relies on HTTP
  4. 4. REST Main ActorsThese are the abstractions that make a RESTful system:• Resources• Representations• Actions
  5. 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. 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.
  7. 7. ActionsActions are used to operate on resourcesThey make up the uniform interface used for client/server data transfers
  8. 8. A Possible Implementation in Java these are annotated HTTP Java classes Resources Jersey Connector/J Driver JDBC mySQL Tomcat
  9. 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. 10. Jersey Suns reference implementation for JAX-RS • Open Source • Production Quality Jersey provides the connectors for web services through Java annotations
  11. 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 only
  12. 12. ResourceA Jersey resource is a plain Java class with a @Path annotationEvery Jersey resource has a URI pointing to it
  13. 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. 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. 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. 16. HTTP Methods: DELETESimilarly to the other methods...* we will see later what @pathParam means
  17. 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. 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. 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. 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. 21. Employee Directory DEMO
  22. 22. Roadmap• REST• Web Sockets• Server-sent Events
  23. 23. Real-time Web? Polling Browser connect Server no message connect no message event connect event connect no message connect no message event connect event
  24. 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. 25. Real-time Web? Long Polling (Comet) Browser Server connect wait event event connect wait event event connect wait
  26. 26. Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• High server loads – memory – threads & processes• Still waste of bandwidth
  27. 27. Real-time Web? Server-Sent Events Browser Server open event stream <EventSource> event event onmessage event event onmessage event onmessage event
  28. 28. Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• only unidirectional
  29. 29. Real-time Web? Web Sockets GET /text HTTP/1.1 Client/Browser Upgrade: WebSocket Server Connection: Upgrade Host: ... HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket ... TCP comm. channel Full duplex, bidirectional
  30. 30. Web SocketsBidirectional, full-duplex communication between full- devices and serverSpecifically suited for chat, videogames, drawings sharing, real-time infoW3C/IETF standard ( a Web Socket Server to handle the protocol
  31. 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. 32. Web Sockets Workflow Handshake Upgrade
  33. 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 one
  34. 34. Web Socket Interface
  35. 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. 36. A Possible Implementation in Java extended HTTP handshake Java Servlet Chat Chat Chat Web Socket Web Socket Web Socket Jetty Server
  37. 37. Chat DEMO
  38. 38. Roadmap• REST• Web Sockets• Server-sent Events
  39. 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. 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 server
  41. 41. Client-Side Interface
  42. 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(; console.log(; these are all the console.log(event.origin); properties of an console.log(event.lastEventId); event}source.addEventListener(‘myEvent, handler, false);
  43. 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. 44. Server-Side SSESyntax of an SSE: <fieldName>: <fieldValue>n
  45. 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. 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. 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. 48. CurrentTime DEMO
  49. 49. References