Server-Side Programming         Primer           Ivano Malavolta      ivano.malavolta@univaq.it  http://www.di.univaq.it/m...
Roadmap• REST• Web Sockets• Server-sent Events
REST (Quick) Refresher    In most cases,    client-server     comunication    relies on HTTPhttp://bit.ly/JALve1
REST Main ActorsThese are the abstractions that make a RESTful system:• Resources• Representations• Actions
ResourcesIn general, a RESTful resource is anything that is   addressable over the WebAddressable = anything that can be a...
RepresentationsThe representation of resources is what is sent back and  forth between clients and serversA URL is a speci...
ActionsActions are used to operate on resourcesThey make up the uniform interface used for  client/server data transfers
A Possible Implementation in Java                                      these are annotated     HTTP                       ...
JAX-RS        Java API for RESTful Web ServicesIt is a Java programming language API that provides  support in creating we...
Jersey     Suns reference implementation for JAX-RS     • Open Source     • Production Quality     Jersey provides the con...
Jersey     The use of annotations allows us to create Jersey       resources just as easily as we develop Plain Old       ...
ResourceA Jersey resource is a plain Java class with a @Path  annotationEvery Jersey resource has a URI pointing to it
HTTP Methods: GETEvery HTTP request made to a web service is handled  by an appropriately annotated method in a resource  ...
HTTP Methods: POSTThe POST request has a payload that the framework  intercepts and delivers to us in the parameter  paylo...
HTTP Methods: PUTSimilar to the POST request, the PUT request has a  payload associated with it, which is stored in the  p...
HTTP Methods: DELETESimilarly to the other methods...* we will see later what @pathParam means
URI Variables@PathParam gives us access to the value of a  variable in a URIWe have to define also one or more String obje...
Input FormatsThe @Consumes annotation tells how to receive  inbound representations from the clientsThe client sets the Co...
Output FormatsThe @Produces annotation tells how to send outbound  representations to the clientsThe client sets the Accep...
Other Annotations• @FormParams    – it lets us read the values of name/value pairs passed in as part      of a POST or PUT...
Employee Directory DEMO
Roadmap• REST• Web Sockets• Server-sent Events
Real-time Web? Polling                            Browser         connect      Server                                     ...
Real-time Web? PollingPROs• Easy to implement via REST• Runs on standard HTTP serversCONs• No real-time user experience• W...
Real-time Web? Long Polling (Comet)                            Browser                      Server                        ...
Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• High server loads   – memory   – threads & process...
Real-time Web? Server-Sent Events                            Browser                            Server                    ...
Real-time Web? Long Polling (Comet)PROs• Real-time user experienceCONs• only unidirectional
Real-time Web? Web Sockets                                               GET /text HTTP/1.1                            Cli...
Web SocketsBidirectional, full-duplex communication between               full-  devices and serverSpecifically suited for...
Web Sockets• What can be sent into a web socket?   – UTF8 Strings   – Binary Frames  it is not a TCP socket   (TCP manages...
Web Sockets Workflow                                                      Handshake                                       ...
Inter-Clients Communication     1. Client notifies websocket server of an event, giving ids of        recipients     2. Th...
Web Socket Interfacehttp://www.w3.org/TR/2009/WD-websockets-20091222/
Drawbacks•   draft standard•   supported by latest browsers only•   some proxies may still block WS handshakes•   need for...
A Possible Implementation in Java                                                    extended                             ...
Chat DEMO
Roadmap• REST• Web Sockets• Server-sent Events
Server-Sent EventsIt setups a persistent http connectionwhich has to be setup only onceIt is unidirectional:      unidirec...
SSE- Overview     1.   Client sends a request to the server via HTTP     2.   The server creates a process, which fetches ...
Client-Side Interfacehttp://dev.w3.org/html5/eventsource/
Client-Side EventsYou can also listen to customized events (not only  generic messagesvar source = new EventSource(“http:/...
Server-Side SSEAn SSE is plain text delivered as part of a stream from  a URLOur data must be treated as a stream
Server-Side SSESyntax of an SSE:         <fieldName>: <fieldValue>n
SSE FieldsfieldName can be:• data (required)   – the information to be sent• event   – the type of event being sent• id   ...
Drawbacks• supported by latest browsers only• browser discrepancies• you need a server that can handle large numbers of  s...
Possible Implementations in Java & PHP  start event stream                         Java Servlet  keep alives  event stream...
CurrentTime DEMO
References
Upcoming SlideShare
Loading in...5
×

Server-Side Programming Primer

1,198

Published on

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

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,198
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
60
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Server-Side Programming Primer

  1. 1. Server-Side Programming Primer Ivano Malavolta ivano.malavolta@univaq.it http://www.di.univaq.it/malavolta
  2. 2. Roadmap• REST• Web Sockets• Server-sent Events
  3. 3. REST (Quick) Refresher In most cases, client-server comunication relies on HTTPhttp://bit.ly/JALve1
  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. http://some.domain.com/orderinfo?id=123
  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 annotationshttps://jersey.dev.java.net
  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 onlyhttps://jersey.dev.java.net
  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 connecthttp://slidesha.re/LeNohX 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 waithttp://slidesha.re/LeNohX 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 eventhttp://slidesha.re/LeNohX 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: www.websocket.org ... HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket ...http://slidesha.re/LeNohX 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 (http://dev.w3.org/html5/websockets)Requires 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 Upgradehttp://code.google.com/p/websocket-sample/wiki/Tips
  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 onehttp://bit.ly/Ixcupi
  34. 34. Web Socket Interfacehttp://www.w3.org/TR/2009/WD-websockets-20091222/
  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 Serverhttp://www.eclipse.org/jetty
  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 serverhttp://bit.ly/Ixcupi
  41. 41. Client-Side Interfacehttp://dev.w3.org/html5/eventsource/
  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(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. 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
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×