Java SSE 服務器推送WEB頁面接收數據


//服務器代碼
package com.xy.inuyasha.web.controller;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
* Created by Administrator on 2017/3/15.
*/
@WebServlet(urlPatterns = { "/role_echo" }, asyncSupported = true)
public class SseTest extends HttpServlet {

private static final long serialVersionUID = 1L;
private final static int DEFAULT_TIME_OUT = 10 * 60 * 1000;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/event-stream");
resp.setCharacterEncoding("UTF-8");
req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);//注意這裏

AsyncContext actx = req.startAsync(req, resp);
actx.setTimeout(DEFAULT_TIME_OUT);
actx.addListener(new AsyncListener() {
@Override
public void onComplete(AsyncEvent arg0) throws IOException {
// TODO Auto-generated method stub
System.out.println("[echo]event complete:" + arg0.getSuppliedRequest().getRemoteAddr());
}

@Override
public void onError(AsyncEvent arg0) throws IOException {
// TODO Auto-generated method stub
System.out.println("[echo]event has error");
}

@Override
public void onStartAsync(AsyncEvent arg0) throws IOException {
// TODO Auto-generated method stub
System.out.println("[echo]event start:" + arg0.getSuppliedRequest().getRemoteAddr());
}

@Override
public void onTimeout(AsyncEvent arg0) throws IOException {
// TODO Auto-generated method stub
System.out.println("[echo]event time lost");
}
});
new Thread(new AsyncWebService(actx)).start();
}
}

class AsyncWebService implements Runnable {
AsyncContext ctx;

public AsyncWebService(AsyncContext ctx) {
this.ctx = ctx;
}

public void run() {
try {
//等待十秒鐘,以模擬業務方法的執行
Thread.sleep(10000);
PrintWriter out = ctx.getResponse().getWriter();
out.println("data:中文" + new Date() + "\r\n"); //js頁面EventSource接收數據格式:data:數據 + "\r\n"

out.flush();
            ctx.complete();
} catch (Exception e) {
e.printStackTrace();
}

}

}
//jsp頁面js腳本
if (!!window.EventSource) { //EventSource是SSE的客戶端.此時說明瀏覽器支持EventSource對象
var source = new EventSource('/role_echo');//發送消息
    s = '';

source.addEventListener('message', function(e) {
                s += e.data + "<br/>";        $("#msgFromPush").html(s);    },false);//添加客戶端的監聽    source.addEventListener('open', function(e) {        console.log("鏈接打開");    }, false);    source.addEventListener('error',function(e){        if(e.currentTarget.readyState==EventSource.CLOSED){            console.log("鏈接關閉");        }else{            console.log(e.currentTarget.readyState);        }    });}else{    console.log("您的瀏覽器不支持SSE");}測試能跑通!!
相關文章
相關標籤/搜索