基於UDP 的servlet 和 html EventSource 的消息推送

今天看了下EventSource的用法,發現仍是有些坑容易讓人掉進去,還不知道是怎麼回事。
html

w3cschool資源:http://www.w3schools.com/html/html5_serversentevents.asp
下面是w3cschool說明的一些注意的地方:
html5

Code explained:

Set the "Content-Type" header to "text/event-stream"
Specify that the page should not cache
Output the data to send (Always start with "data: ")
Flush the output data back to the web page
另外,eventSource的源必須和和html在同一服務下
 html端實現我就不寫了, w3cschool裏面都有。
如下是Java端
public class UDPStreamServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(UDPStreamServlet.class);
	//udp server
	private static DatagramSocket serverSocket ;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		   //最大接收的數據
	       byte[] receiveData = new byte[1024*512];
	       DatagramPacket receivePacket = null;
	       resp.setHeader("Content-Type", "text/event-stream;charset=UTF-8");
	       resp.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
	        while(true) {
	        	receiveData = new byte[1024*512];
	        	receivePacket = new DatagramPacket(receiveData,
						receiveData.length);
	        	//接收數據
	        	serverSocket.receive(receivePacket);
	        	//data:必須寫過去,否則顯示不出來
	        	resp.getWriter().print("data:");
	        	//實際接收到的數據
	        	resp.getWriter().println(new String(receivePacket.getData()).trim());
	        	//得有一個空白行,否則出錯
	        	resp.getWriter().println();
	        	resp.getWriter().flush(); 
	        }
	            
	}
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req,resp);
	}

	@Override
	public void destroy() {
		if(serverSocket!=null){
			//關閉udp服務端
			serverSocket.close();
		}
		super.destroy();
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		String udpPort  = config.getInitParameter("udpPort");
		int port = Integer.valueOf(udpPort);
		System.out.println("-->udpPort="+port);
		try {
			serverSocket = new DatagramSocket(port);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
相關文章
相關標籤/搜索