服务器端的推送

2019-03-15 110 words 1 min read

SSE(EventSource)实时通信

Event-source必须编码成utf-8的格式,消息的每个字段使用“\n”来做分割,并且需要下面4个规范定义好的字段:

  1. Event: 事件类型
  2. Data: 发送的数据
  3. ID: 每一条事件流的ID
  4. Retry: 告知浏览器在所有的连接丢失之后重新开启新的连接等待的时间,在自动重新连接的过程中,之前收到的最后一个事件流ID会被发送到服务端。

前端调用:

if(typeof(EventSource)!="undefined"){
	/*浏览器支持 Server-Sent*/
	var es = new EventSource("/url");
	es.onmessage = function(e) {
		var json=JSON.parse(e.data);
		if(json.isLogin){
		
		}else{
		
		}
	};
}else{	
	/*浏览器不支持 Server-Sent*/
	console.log("浏览器不支持Html5的SSE功能!");
}


后端响应:

@RequestMapping(value = "/url", produces = "text/event-stream")
public String isLogin() throws Exception {
	SSEResult result = new SSEResult();
	result.setId("isLogin");
	result.setEvent("isLogin");
	result.setRetry(10000 + 1000L); /*11s*/
	result.addData("isLogin", true/false);
	return result.toString();
}

返回字符串处理:

public String toString() {
	StringBuilder sb = new StringBuilder();
	if (StringUtils.isNotBlank(this.event)) {
		sb.append("event:").append(this.event).append("\n\n");
	}
	if (StringUtils.isNotBlank(this.id)) {
		sb.append("id:").append(this.id).append("\n\n");
	}
	if (this.retry != null && this.retry > 0) {
		sb.append("retry:").append(this.retry).append("\n\n");
	}
	if (MapUtils.isNotEmpty(this.datas)) {
		Gson gson = new GsonBuilder().create();
		String dataStr = gson.toJson(this.datas);
		sb.append("data:").append(dataStr).append("\n\n");
	}
	return sb.toString();
}


Tags: sse

author

Authored By WUHAOTIAN

A gentleman should always strive to improve himself

We notice you're using an adblocker. If you like our webite please keep us running by whitelisting this site in your ad blocker. We’re serving quality, related ads only. Thank you!

I've whitelisted your website.

Not now
This website uses cookies to ensure you get the best experience on our website. Learn more Got it