com.sishuok.chapter3.web.controller.StreamingController.java Source code

Java tutorial

Introduction

Here is the source code for com.sishuok.chapter3.web.controller.StreamingController.java

Source

/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.sishuok.chapter3.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * streaming
 *
 * spring mvc??streaming??
 *
 * ??chapter3com.sishuok.chapter3.web.servlet.AsyncServlet3
 *
 * <p>User: Zhang Kaitao
 * <p>Date: 13-7-18 ?8:05
 * <p>Version: 1.0
 */
@Controller
public class StreamingController {

    private final Queue<AsyncContext> queue = new ConcurrentLinkedQueue();

    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //?????? + iframe???
                while (true) {
                    //
                    try {
                        Thread.sleep(5L * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //???? ??AsyncContext
                    Iterator<AsyncContext> iter = queue.iterator();
                    while (iter.hasNext()) {
                        AsyncContext asyncContext = iter.next();
                        // ??
                        try {
                            ServletResponse response = asyncContext.getResponse();
                            PrintWriter out = response.getWriter();
                            String msg = "new message : " + System.currentTimeMillis();
                            out.write("<script>parent.callback('" + msg + "');</script>");
                            try {
                                response.flushBuffer();
                            } catch (IOException e) {
                                //? 
                                iter.remove();
                                asyncContext.complete();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //                    System.out.println("push message count : " + queue.size());
                }
            }
        }).start();
    }

    @RequestMapping("/async3")
    public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setHeader("Connection", "Keep-Alive");
        resp.addHeader("Cache-Control", "private");
        resp.addHeader("Pragma", "no-cache");
        resp.setContentType("text/html;charset=utf-8");
        resp.flushBuffer();

        //1??
        final AsyncContext asyncContext = req.startAsync();

        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(final AsyncEvent event) throws IOException {
                queue.remove(event.getAsyncContext());
            }

            @Override
            public void onTimeout(final AsyncEvent event) throws IOException {
                event.getAsyncContext().complete();
                queue.remove(event.getAsyncContext());
            }

            @Override
            public void onError(final AsyncEvent event) throws IOException {
                queue.remove(event.getAsyncContext());
            }

            @Override
            public void onStartAsync(final AsyncEvent event) throws IOException {
            }
        });

        //????
        queue.add(asyncContext);

    }
}