HTML Server-sent implements server push messages to HTML pages

The following is a simple implementation of pushing messages to HTML pages from the JAVA background.

Code behind (put the method in the Controller):
public String getPushMessage(){
		String message="msg";
		getResponse().setContentType("text/event-stream;charset=UTF-8");
		getResponse().setCharacterEncoding("UTF-8");
		try {
			PrintWriter writer=getResponse().getWriter();
			writer.write("data: "+message+"\n\n");//Be sure to end with \n\n
			writer.close();
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return null;
	}


Front desk code:
$(function(){
	if(window.Notification){
		if(window.Notification.permission != "granted"){
			window.Notification.requestPermission();
		}
	}
	else{
		alert('Your browser does not support this message prompt function, please use a browser with chrome core!');
	}
	var eventSource=new EventSource("getPushMessage");
	eventSource.onmessage=function(event){
		var message=event.data;
		alert(message);
        //The function of the following code is to enable the message to pop up on the windows desktop (it doesn't matter if the HTML page is minimized)
        var notification = new Notification("title", {
        body: message,
        icon: 'img/title.jpg',
        requireInteraction:true//Indicates need to interact with the user, that is: the user clicks to close the pop-up window to disappear
            });
	}
});

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326979128&siteId=291194637