Server-Side Programming Primer
-
Upload
ivano-malavolta -
Category
Education
-
view
1.116 -
download
0
description
Transcript of Server-Side Programming Primer
Server-Side ProgrammingServer-Side ProgrammingPrimer
Ivano MalavoltaIvano Malavolta
http://www.di.univaq.it/malavolta
Roadmap
• REST
• Web Sockets• Web Sockets
• Server-sent Events
REST (Quick) Refresher
In most cases, client-server client-server comunicationrelies on HTTP
http://bit.ly/JALve1
REST Main Actors
These are the abstractions that make a RESTful system:
• ResourcesResourcesResourcesResources
• RepresentationsRepresentationsRepresentationsRepresentations
• ActionsActionsActionsActions
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
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
Actions
Actions are used to operate on resources
They make up the uniform interface used for client/server data transfers
A Possible Implementation in Java
HTTP
these are annotatedJava classes
JerseyResources
mySQL
Tomcat
Connector/J Driver JDBC
Jersey
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
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
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
Resource
A Jersey resource is a plain Java class with a @Path annotationannotation
Every Jersey resource has a URI pointing to it
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
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)
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
HTTP Methods: DELETE
Similarly 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 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
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
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
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
• ...
Employee Directory DEMO
Roadmap
• REST
• Web Sockets• Web Sockets
• Server-sent Events
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
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
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
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
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
Real-time Web? Long Polling (Comet)
PROsPROsPROsPROs
• Real-time user experience• Real-time user experience
CONsCONsCONsCONs
• only unidirectional• only unidirectional
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
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
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://
Web Sockets Workflow
HandshakeHandshakeHandshakeHandshakeUpgradeUpgradeUpgradeUpgradeUpgradeUpgradeUpgradeUpgrade
http://code.google.com/p/websocket-sample/wiki/Tips
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
Web Socket Interface
http://www.w3.org/TR/2009/WD-websockets-20091222/
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
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
Chat DEMO
Roadmap
• REST
• Web Sockets• Web Sockets
• Server-sent Events
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)
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
Client-Side Interface
http://dev.w3.org/html5/eventsource/
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
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 �
Server-Side SSE
Syntax of an SSE: <fieldName>: <fieldValue>\n<fieldName>: <fieldValue>\n
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
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
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
CurrentTime DEMO
References