用于接收和共享流数据的Servlet

时间:2018-04-20 14:52:34

标签: java multithreading jsp servlets

我有三个程序(b - c - a):b启动c处理c,{{1}结束a重新启动b。我只能更改b,但它不稳定,因为它已重新启动。我正在考虑使用接收b数据和错误的servlet服务解决我的问题,并立即将它们显示在网页上。我尝试了两种方法:1。以与{servlet)并行的Thread接收数据并与之共享(我没有成功); 2.从客户端接收数据并与ServletContext共享,并使用已发送事件刷新页面,但跳过行,即使重试:100,并在没有新数据时重复最后一行。有没有办法只在新的时候将数据发送到所有servlet客户端?考虑到b重新启动并且我必须限制使用的端口,是否有更好的解决方案?

- UPDATE-- Servlet.java

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.*;

@WebServlet(name = "Servlet", urlPatterns = {"/Servlet", "/test"})
public class Servlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Connection", "keep-alive");
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        String datain = request.getParameter("StringIn");
        String dataold = request.getParameter("StringOld");
        PrintWriter writer = response.getWriter();

        if (datain == null) {
            boolean test = getServletContext().getAttribute("actualData").equals(request.getParameter("StringOld"));
            if (!test) {
                writer.write("data: " + getServletContext().getAttribute("actualData") +"\n\n");
                writer.write("retry: 500");
            }
            else {
                writer.write("data: \n\n");
                writer.write("retry: 1000");
            }
        }
        else {
            getServletContext().setAttribute("actualData", datain);
            writer.write("data receive!\n\n");
        }
        writer.flush();
        writer.close();
    }
}

脚本index.jsp

var eventSource = null;
var oldmessage = "";
var path = "http://localhost:8080/Servlet?StringaOld=";
function start() {
    eventSource = new EventSource(path + oldmessage);
    eventSource.onopen = function () {
    };
    eventSource.onmessage = function (message) {
        var mex = message.data;
        message.data = null;
        if (mex != null) {
            oldmex = mex;
            testo.value += mex + "\n";
        }
    };
    eventSource.onerror = function (error) {
        eventSource = new EventSource(path + encodeURI(oldmessage));
    };
    Start.disabled = true;
}

function stop() {
    eventSource.close();
    Start.disabled = false;
}

0 个答案:

没有答案