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

Server-Side Programming Primer

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Server-Side Programming Primer

Server-Side ProgrammingServer-Side ProgrammingPrimer

Ivano MalavoltaIvano Malavolta

[email protected]

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

Page 2: Server-Side Programming Primer

Roadmap

• REST

• Web Sockets• Web Sockets

• Server-sent Events

Page 3: Server-Side Programming Primer

REST (Quick) Refresher

In most cases, client-server client-server comunicationrelies on HTTP

http://bit.ly/JALve1

Page 4: Server-Side Programming Primer

REST Main Actors

These are the abstractions that make a RESTful system:

• ResourcesResourcesResourcesResources

• RepresentationsRepresentationsRepresentationsRepresentations

• ActionsActionsActionsActions

Page 5: Server-Side Programming Primer

Resources

In general, a RESTful resource is anything that is anything that is anything that is anything that is addressable over the Webaddressable over the Webaddressable over the Webaddressable over the Webaddressable over the Webaddressable over the Webaddressable over the Webaddressable over the Web

AddressableAddressableAddressableAddressable ==== 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 URIsURIsURIsURIs

ex..../orderinfo?id=123

Page 6: Server-Side Programming Primer

Representations

The representationrepresentationrepresentationrepresentation of resources is what is sent back and forth between clients and servers

A URLURLURLURL is a specialization of URI that defines the network location of a specific resource

es. http://some.domain.com/orderinfo?id=123

Page 7: Server-Side Programming Primer

Actions

Actions are used to operate on resources

They make up the uniform interface used for client/server data transfers

Page 8: Server-Side Programming Primer

A Possible Implementation in Java

HTTP

these are annotatedJava classes

JerseyResources

mySQL

Tomcat

Connector/J Driver JDBC

Jersey

Page 9: Server-Side Programming Primer

JAX-RS

Java API for Java API for Java API for Java API for RESTfulRESTfulRESTfulRESTful Web ServicesWeb ServicesWeb ServicesWeb Services

It is a Java programming language API that provides support in creating web services according to the REST architectural style

Many ImplementationsApache CXF

Many ImplementationsApache CXF

Restlet

RESTEasyJersey

Wink

Page 10: Server-Side Programming Primer

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 annotationsJava annotationsJava annotationsJava annotations

https://jersey.dev.java.net

Page 11: Server-Side Programming Primer

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

Page 12: Server-Side Programming Primer

Resource

A Jersey resource is a plain Java class with a @Path annotationannotation

Every Jersey resource has a URI pointing to it

Page 13: Server-Side Programming Primer

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

Page 14: Server-Side Programming Primer

HTTP Methods: POST

The POST request has a payloadpayloadpayloadpayload 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)

Page 15: Server-Side Programming Primer

HTTP Methods: PUT

Similar to the POST request, the PUT request has a payloadpayloadpayloadpayload associated with it, which is stored in the payloadpayloadpayloadpayload associated with it, which is stored in the payload variable

* we will see later what @Consumes and @PathParam mean

Page 16: Server-Side Programming Primer

HTTP Methods: DELETE

Similarly to the other methods...

* we will see later what @pathParam means

Page 17: Server-Side Programming Primer

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

Page 18: Server-Side Programming Primer

Input Formats

The @Consumes annotation tells how to receive inbound representations from the clientsinbound 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

Page 19: Server-Side Programming Primer

Output Formats

The @Produces annotation tells how to send outbound representations to the clientsrepresentations 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

Page 20: Server-Side Programming Primer

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

• ...

Page 21: Server-Side Programming Primer

Employee Directory DEMO

Page 22: Server-Side Programming Primer

Roadmap

• REST

• Web Sockets• Web Sockets

• Server-sent Events

Page 23: Server-Side Programming Primer

Real-time Web? Polling

connect

no message

connect

Browser Server

connect

no messageevent

connect

event

connectno message

http

://slide

sha.re

/LeN

ohX

no message

connectno message eventconnectevent

http

://slide

sha.re

/LeN

ohX

Page 24: Server-Side Programming Primer

Real-time Web? Polling

PROsPROsPROsPROs• Easy to implement via REST• Easy to implement via REST• Runs on standard HTTP servers

CONsCONsCONsCONs• No real-time user experience• Wasted bandwidth• Wasted bandwidth

– most requests return no data

• High server loads

Page 25: Server-Side Programming Primer

Real-time Web? Long Polling (Comet)

connectBrowser Server

wait

eventevent

wait

connect

wait

http

://slide

sha.re

/LeN

ohX

eventevent

connect

wait

http

://slide

sha.re

/LeN

ohX

Page 26: Server-Side Programming Primer

Real-time Web? Long Polling (Comet)

PROsPROsPROsPROs

• Real-time user experience• Real-time user experience

CONsCONsCONsCONs

• High server loads• High server loads– memory

– threads & processes

• Still waste of bandwidth

Page 27: Server-Side Programming Primer

Real-time Web? Server-Sent Events

open event streamServer

<EventSource>

Browser

eventevent

eventevent

eventevent

onmessage

onmessage

onmessage

http

://slide

sha.re

/LeN

ohX

eventonmessage

http

://slide

sha.re

/LeN

ohX

Page 28: Server-Side Programming Primer

Real-time Web? Long Polling (Comet)

PROsPROsPROsPROs

• Real-time user experience• Real-time user experience

CONsCONsCONsCONs

• only unidirectional• only unidirectional

Page 29: Server-Side Programming Primer

Real-time Web? Web SocketsClient/Browser ServerGET /text HTTP/1.1GET /text HTTP/1.1GET /text HTTP/1.1GET /text HTTP/1.1

Upgrade: WebSocket Upgrade: WebSocket Upgrade: WebSocket Upgrade: WebSocket Connection: UpgradeConnection: UpgradeConnection: UpgradeConnection: UpgradeHost: www.websocket.org ...Host: www.websocket.org ...Host: www.websocket.org ...Host: www.websocket.org ...

HTTP/1.1 101 WebSocket Protocol HandshakeHTTP/1.1 101 WebSocket Protocol HandshakeHTTP/1.1 101 WebSocket Protocol HandshakeHTTP/1.1 101 WebSocket Protocol HandshakeUpgrade: WebSocket ...Upgrade: WebSocket ...Upgrade: WebSocket ...Upgrade: WebSocket ...

http

://slide

sha.re

/LeN

ohX

TCP comm. TCP comm. TCP comm. TCP comm. channelchannelchannelchannelFull duplex, bidirectionalFull duplex, bidirectionalFull duplex, bidirectionalFull duplex, bidirectional

http

://slide

sha.re

/LeN

ohX

Page 30: Server-Side Programming Primer

Web Sockets

Bidirectional, fullBidirectional, fullBidirectional, fullBidirectional, full----duplex communicationduplex communicationduplex communicationduplex communication between devices and server

Specifically suited forchat, 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

Page 31: Server-Side Programming Primer

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

Page 32: Server-Side Programming Primer

Web Sockets Workflow

HandshakeHandshakeHandshakeHandshakeUpgradeUpgradeUpgradeUpgradeUpgradeUpgradeUpgradeUpgrade

http://code.google.com/p/websocket-sample/wiki/Tips

Page 33: Server-Side Programming Primer

Inter-Clients Communication

1.1.1.1. Client notifies Client notifies Client notifies Client notifies websocketwebsocketwebsocketwebsocket server server server server of an event, giving ids of recipientsrecipients

2. The serverserverserverserver 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

Page 34: Server-Side Programming Primer

Web Socket Interface

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

Page 35: Server-Side Programming Primer

Drawbacks

• draftdraftdraftdraft standard• supported by latestlatestlatestlatest browsersbrowsersbrowsersbrowsers only• supported by latestlatestlatestlatest browsersbrowsersbrowsersbrowsers only• some proxiesproxiesproxiesproxies may still block WS handshakes• need for keepkeepkeepkeep----alivealivealivealive messagesmessagesmessagesmessages• need to manually manage messagemessagemessagemessage queuesqueuesqueuesqueues• every encountered problem results in closingclosingclosingclosing the the the the

connectionconnectionconnectionconnectionconnectionconnectionconnectionconnection� you cannot distinguish between:

• client or server errors• network errors• timeouts

Page 36: Server-Side Programming Primer

A Possible Implementation in Java

extendedJava Servlet

HTTP handshake

Chat Web Socket

Chat Web Socket

Chat Web Socket

Jetty Server

Web Socket

http://www.eclipse.org/jetty

Page 37: Server-Side Programming Primer

Chat DEMO

Page 38: Server-Side Programming Primer

Roadmap

• REST

• Web Sockets• Web Sockets

• Server-sent Events

Page 39: Server-Side Programming Primer

Server-Sent Events

It setups a persistent http connection persistent http connection persistent http connection persistent http connection which has to be setup only oncewhich has to be setup only once

It is unidirectionalunidirectionalunidirectionalunidirectional: : : : server � client

SSEs are sent over traditional HTTPSSEs are sent over traditional HTTPSSEs are sent over traditional HTTPSSEs are sent over traditional HTTP� it can be easily implemented with standard server-side technologies (eg PHP)

Page 40: Server-Side Programming Primer

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 backresponds backresponds backresponds back

3. Client gets server responsegets server responsegets server responsegets 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

Page 41: Server-Side Programming Primer

Client-Side Interface

http://dev.w3.org/html5/eventsource/

Page 42: Server-Side Programming Primer

Client-Side Events

You can also listen to customized events (not onlygeneric messagesgeneric 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 anconsole.log(event.origin);

console.log(event.lastEventId);

}

source.addEventListener(‘myEvent', handler, false);

properties of anevent

Page 43: Server-Side Programming Primer

Server-Side SSE

An SSE is plain text delivered as part of a stream from a URLa URL

Our data must be treated as a stream �

Page 44: Server-Side Programming Primer

Server-Side SSE

Syntax of an SSE: <fieldName>: <fieldValue>\n<fieldName>: <fieldValue>\n

Page 45: Server-Side Programming Primer

SSE Fields

fieldName can be:

• data (required)data (required)data (required)data (required)– the information to be sent

• eventeventeventevent– the type of event being sent

• idididid– an identifier for the event to be used when the client – an identifier for the event to be used when the client

reconnects• retryretryretryretry

– how much time (in milliseconds) should pass before the client tries to reconnect to the URL

Page 46: Server-Side Programming Primer

Drawbacks

• supported by latestlatestlatestlatest browsersbrowsersbrowsersbrowsers only

• browser browser browser browser discrepanciesdiscrepanciesdiscrepanciesdiscrepancies• browser browser browser browser discrepanciesdiscrepanciesdiscrepanciesdiscrepancies

• 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 dropdropdropdrop the HTTP connection the HTTP connection the HTTP connection the HTTP connection after a short timeout

Page 47: Server-Side Programming Primer

Possible Implementations in Java & PHP

Java Servletstart event stream

keep alives

Jetty Server

Java Servletkeep alives

event stream

start event stream

Apache Server

PHP Pagestart event stream

keep alives

event stream

Page 48: Server-Side Programming Primer

CurrentTime DEMO

Page 49: Server-Side Programming Primer

References