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

今天看了下EventSource的用法,发现还是有些坑容易让人掉进去,还不知道是怎么回事。

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

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();
		}
	}



你可能感兴趣的:(servlet,UDP,EventSource,的消息推送)