Slide 1

Slide 1 text

Server-Side Programming Server-Side Programming Primer Ivano Malavolta Ivano Malavolta [email protected] http://www.di.univaq.it/malavolta

Slide 2

Slide 2 text

Roadmap • REST • Web Sockets • Web Sockets • Server-sent Events

Slide 3

Slide 3 text

REST (Quick) Refresher In most cases, client-server client-server comunication relies on HTTP http://bit.ly/JALve1

Slide 4

Slide 4 text

REST Main Actors These are the abstractions that make a RESTful system: • Resources Resources Resources Resources • Representations Representations Representations Representations • Actions Actions Actions Actions

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

Actions Actions are used to operate on resources They make up the uniform interface used for client/server data transfers

Slide 8

Slide 8 text

A Possible Implementation in Java HTTP these are annotated Java classes Jersey Resources mySQL Tomcat Connector/J Driver JDBC Jersey

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

Resource A Jersey resource is a plain Java class with a @Path annotation annotation Every Jersey resource has a URI pointing to it

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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)

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

HTTP Methods: DELETE Similarly to the other methods... * we will see later what @pathParam means

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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 • ...

Slide 21

Slide 21 text

Employee Directory DEMO

Slide 22

Slide 22 text

Roadmap • REST • Web Sockets • Web Sockets • Server-sent Events

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

Real-time Web? Server-Sent Events open event stream Server Browser event event event event event event onmessage onmessage onmessage http://slidesha.re/LeNohX event onmessage http://slidesha.re/LeNohX

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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://

Slide 32

Slide 32 text

Web Sockets Workflow Handshake Handshake Handshake Handshake Upgrade Upgrade Upgrade Upgrade Upgrade Upgrade Upgrade Upgrade http://code.google.com/p/websocket-sample/wiki/Tips

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Web Socket Interface http://www.w3.org/TR/2009/WD-websockets-20091222/

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

Chat DEMO

Slide 38

Slide 38 text

Roadmap • REST • Web Sockets • Web Sockets • Server-sent Events

Slide 39

Slide 39 text

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)

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

Client-Side Interface http://dev.w3.org/html5/eventsource/

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

Server-Side SSE Syntax of an SSE: : \n : \n

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

CurrentTime DEMO

Slide 49

Slide 49 text

References