RESTful Web Services – Server-Sent Events (SSE)

Exclusive offer: get 50% off this eBook here
Developing RESTful Web Services with Jersey 2.0

Developing RESTful Web Services with Jersey 2.0 — Save 50%

Create RESTful web services smoothly using the robust Jersey 2.0 and JAX-RS APIs with this book and ebook

€16.99    €8.50
by Sunil Gulabani | November 2013 | Web Services Open Source Web Development

In this article by Sunil Gulabani, author of the book Developing RESTful Web Services with Jersey 2.0, we will learn about how to create a connection between the client/server and maintain the connection at the server's end. This is needed to push the data from the server to the client without any new request initiated by the client. This type of mechanism is basically used for applications such as chatting, stock market, or any real-time data-providing applications.

(For more resources related to this topic, see here.)

Getting started

Generally, the flow of web services is initiated by the client by sending a request for the resource to the server. This is the traditional way of consuming web services.

Traditional Flow

Here, the browser or Jersey client initiates the request for data from the server, and the server provides a response along with the data. Every time a client needs to initiate a request for the resource, the server may not have the capability to generate the data. This becomes difficult in an application where real-time data needs to be shown. Even though there is no new data over the server, the client needs to check for it every time.

Nowadays, there is a requirement that the server needs to send some data without the client's request. For this to happen the client and server need to be connected, and the server can push the data to the client. This is why it is termed as Server-Sent Events. In these events, the connections created initially between the client and server is not released after the request. The server maintains the connection and pushes the data to the respective client when required.

Server-Sent Event Flow

In the Server-Sent Event Flow diagram initially, when a browser or a Jersey client initiates a request to establish a connection with the server using EventSource, the server is always in a listening mode for the new connection to be established. When a new connection from any EventSource is received, the server opens a new connection and maintains it in a queue. Maintaining a connection depends upon the implementation of business logic. SSE creates a single unidirectional connection. So, only a single connection is established between the client and server.

After the connection is successfully established, the client is in the listening mode for new events from the server. Whenever any new event occurs on the server side, it will broadcast the event, along with the data to a specific open HTTP connection. In modern browsers that support HTML5, the onmessage method of EventSource is responsible for handling new events received from the server; whereas, in the case of Jersey clients, we have the onEvent method of EventSource, which handles new events from the server.

Implementing Server-Sent Events (SSE)

To use SSE, we need to register SseFeature on both the client and server sides. By doing so, the client/server gets connected to SseFeature to be used while traversing data over the network.

SSE: Internal Working

In the SSE: Internal Working diagram, we assume that the client/server is connected. When any new event is generated, the server initiates an OutboundEvent instance that will be responsible to have chunked output, which in turn will have a serialized data format. OutboundEventWriter is responsible to serialize the data on the server side. We need to specify the media type of the data in OutboundEvent. There are no restrictions of providing specific media types only.

However, on the client side, InboundEvent is responsible for handling the incoming data from the server. Here, InboundEvent receives the chunked input that contains serialized data format. Using InbounEventReader, data is deserialized.

Using SSEBroadCaster, we are able to broadcast events to multiple clients that are connected to the server. Let's look at the example, which shows how to create SSE web services and broadcast the events:

@ApplicationPath("services") public class SSEApplication extends ResourceConfig { publicSSEApplication() { super(SSEResource.class, SseFeature.class); } }

Here, we registered the SseFeature module and the SSEResource root-resource class to the server.

private static final SseBroadcaster BROADCASTER = new SseBroadcaster(); …… @GET @Path("sseEvents") @Produces(SseFeature.SERVER_SENT_EVENTS) public EventOutput getConnection() { final EventOutput eventOutput = new EventOutput(); BROADCASTER.add(eventOutput); return eventOutput; } ……

In the SSEResource root class, we need to create a resource method that will allow clients to establish the connection and persist accordingly. Here, we are maintaining the connection into the BROADCASTER instance in the SseBroadcaster class. EventOutput manages specific client connections. SseBroadcaster is simply responsible for accommodating a group of EventOutput; that is, the client's connection.

…… @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void post(@FormParam("name") String name) { BROADCASTER .broadcast(new OutboundEvent.Builder() .data(String.class, name) .build()); } ……

When any post method is consumed, we create a new event and broadcast it to the client available in the BROADCASTER instance. The OutboundEvent instance will contain the data (MediaType, Object) method that is initialized with a specific media type and actual data. We can provide any media type to send data. By using the build() method, data is being serialized with the OutBoundEventWriter class internally. When the broadcast (OutboundEvent) is called, internally SseBroadcaster pushes data on all registered EventOutputs; that is, on clients connected to SseBroadcaster.

At times, there's a scenario where the client/server has been connected and after sometime, the client gets disconnected. So, in this case, SseBroadcaster automatically handles the client connection; that is, it determines whether the connection needs to be maintained. When any client connection is closed, the broadcaster detects EventOutput and frees the connection and resources obtained by that EventOutput connection.

Summary

Thus we learned the difference between the traditional web service flow and SSE web service flow. We also covered how to create the SSE web services and implement the Jersey client in order to consume the SSE using different programmatic models.

Resources for Article :


Further resources on this subject:


Developing RESTful Web Services with Jersey 2.0 Create RESTful web services smoothly using the robust Jersey 2.0 and JAX-RS APIs with this book and ebook
Published: November 2013
eBook Price: €16.99
Book Price: €26.99
See more
Select your format and quantity:

About the Author :


Sunil Gulabani

Sunil Gulabani is a software engineer based in Ahmedabad, Gujarat (India). He completed his graduation in Commerce from S M Patel Institute of Commerce (SMPIC) and Masters in Computer Applications from Ahmedabad Education Society Institute of Computer Studies (AESICS). He has been a top ranker while pursuing his master's degree. He has also presented a paper "Effective Label Matching For Automated Evaluation of Use Case Diagrams" on Technology For Education (T4E)—IIIT. Hyderabad, an IEEE Conference, along with senior lecturers, Vinay Vachharajani and Dr. Jyoti Pareek.

He has been working since 2011 as a software engineer, and is Cloud technology savvy. He has experience in developing enterprise solutions using Java (EE), Apache SOLR, RESTful web services, GWT, SmartGWT, Amazon web services (AWS), Redis, Memcache, MongoDB, and so on. He has a keen interest in system architecture and integration, data modeling, relational databases, and mapping with NoSQL for high throughput.

Apart from that, he takes interest in writing tech blogs and is actively involved in a knowledge-sharing community named Java User Group Ahmedabad (JUG-Ahmedabad).

You can visit him online at http://www.sunilgulabani.com and follow him on Twitter at twitter.com/sunil_gulabani, or reach him directly at sunil_gulabani@yahoo.com.

Books From Packt


RESTful PHP Web Services
RESTful PHP Web Services

Web Services Testing with soapUI
Web Services Testing with soapUI

PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax
PHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax

RESTful Java Web Services
RESTful Java Web Services

Java 7 JAX-WS Web Services
Java 7 JAX-WS Web Services

Spring Web Flow 2 Web Development
Spring Web Flow 2 Web Development

Alfresco 3 Web Services
Alfresco 3 Web Services

Ruby on Rails Web Mashup Projects
Ruby on Rails Web Mashup Projects

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software