2016년 3월 9일 수요일

Data Push Apps with HTML5 SSE


Data Push with HTML5 SSE

SSE stands for Server-Sent Event and it is an HTML5 technology to allow the server to push fresh data to clients. It is a superior solution to having the client poll for new data every few seconds.

Data Push
Server-Sent Events(SSE) is an HTML5 technology that allows the server to push fresh data to client(commonly called data pusy).

That is what data push isn’t. It is not static files. And it is not a request made by the
browser for the latest data. Data push is where the server chooses to send new data to
the clients.
When the data source has new data, it can send it to the client(s) immediately, without
having to wait for them to ask for it. This new data could be breaking news, the latest
stock market prices, a chat message from another online friend, a new weather forecast,
the next move in a strategy game, etc.

Other Names for Data Push
The need for data push is as old as the Web,1 and over the years people have found many
novel solutions, most of them with undesirable compromises. You may have heard of
some other technologies—Comet, Ajax Push, Reverse Ajax, HTTP Streaming—and be
wondering what the difference is between them. These are all talking about the same
thing: SSE was added as an
HTML5 technology to have something that is both easy to use and efficient. If your
browser supports it, SSE is always2 superior to the Comet technologies.
By the way, you will sometimes see SSE referred to as EventSource, because that is the
name of the related object in JavaScript. I will call it SSE everywhere in this book, and
I will only use EventSource to refer to the JavaScript object.


Comparison with WebSockets
WebSockets is a more complicated technology to implement server side, but it is a real
two-way socket, which means the server can push data to the client and the client can
push data back to the server.
SSE has a few notable advantages over WebSockets. For me the biggest of those is convenience:
you don’t need any new components—just carry on using whatever backend
language and frameworks you are already used to. You don’t need to dedicate a new
virtual machine, a new IP, or a new port to it. It can be added just as easily as adding
another page to an existing website. I like to think of this as the existing infrastructure
advantage.
The second advantage is server-side simplicity. As we will see in Chapter 2, the backend
code is literally just a few lines. In contrast, the WebSockets protocol is complicated and
you would never think to tackle it without a helper library. (I did; it hurt.)
Because SSE works over the existing HTTP/HTTPS protocols, it works with existing
proxy servers and existing authentication techniques; proxy servers need to be made
WebSocket aware, and at the time of writing many are not (though this situation will
improve). This also ties into another advantage: SSE is a text protocol and you can debug
your scripts very easily. In fact, in this book we will use curl and will even run our
backend scripts directly at the command line when testing and developing.
But that leads us directly into a potential advantage of WebSocket over SSE: it is a binary
protocol, whereas SSE uses UTF-8. Sure, you could send binary data over the SSE connection:
the only characters with special meaning in SSE are CR and LF, and those are
easy to escape. But binary data is going to be bigger when sent over SSE. If you are
sending large amounts of binary data from server to client, WebSockets is the better
choice.

But the biggest advantage of WebSockets over SSE is that it is two-way communication.


http://caniuse.com/#search=eventsource
Any recent version of Firefox, Chrome, Safari, iOS Safari, or Opera will work. It won’t work on IE11 and earlier. It also won’t work on the native browser in Android 4.3 and earlier.

SSE Example Code

Client Side Code : index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SSE Test Page</title>
<body>
   Time: <span id="foo"></span>
    
   <br><br>
   <button onclick="start()">Start</button>
   <script type="text/javascript">
   function start() {
       var eventSource = new EventSource("./SSEHelloServlet");
        
       eventSource.onmessage = function(event) {
        
           document.getElementById('foo').innerHTML = event.data;
        
       };
        
   }
   </script>
</body>
</html>

Server Sent Event Code: SSEHelloServlet

package kr.blogspot.daddycat.sse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class SSEHelloServlet
*/
@WebServlet("/SSEHelloServlet")
public class SSEHelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* Default constructor.
*/
public SSEHelloServlet() {
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// content type must be set to text/event-stream
response.setContentType("text/event-stream");

// encoding must be set to UTF-8
response.setCharacterEncoding("UTF-8");

PrintWriter writer = response.getWriter();

for (int i = 0; i < 10; i++) {

writer.write("data: "
+ Calendar.getInstance(Locale.KOREA).getTime() + "\n\n");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
writer.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}




and Click the ‘Start’ Button.

댓글 없음:

댓글 쓰기

블록체인 개요 및 오픈소스 동향

블록체인(block chain) 블록체인은 공공 거래장부이며 가상 화폐로 거래할때 발생할때 발생할 수 있는 해킹을 막는 기술. 분산 데이터베이스의 한 형태로, 지속적으로 성장하는 데이터 기록 리스트로서 분산 노드의 운영자에 의한 임의 조작이 불가...