tomcat-websocket实现后台消息推动到浏览器

主要依赖

实现APP端提交一条预约订单时,将预约信息实时提示到pc端页面

<properties>
		<!--maven插件变量 -->
		<spring.version>3.1.1.RELEASE</spring.version>
		<tomcat.version>2.2</tomcat.version>
		<webserver.port>8080</webserver.port>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- tomcat-websocket -->
	 <dependency>
           <groupId>javax.websocket</groupId>
           <artifactId>javax.websocket-api</artifactId>
           <version>1.1</version>
           <scope>provided</scope>
  	</dependency>
</dependencies>
<build>
	<finalName>${project.artifactId}</finalName>
	<!-- tomcat7插件 -->
	<plugin>
		<groupId>org.apache.tomcat.maven</groupId>
		<artifactId>tomcat7-maven-plugin</artifactId>
		<version>${tomcat.version}</version>
		<configuration>
			<port>${webserver.port}</port>
			<path>/${project.artifactId}</path>
			<uriEncoding>${project.build.sourceEncoding}</uriEncoding>
		</configuration>
	</plugin>
</build>
package com.loan.spmkt.intercepto;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;;

@ServerEndpoint("/webServlet")
public class WsCtrl {
	
	private Session session;
	
	private static ConcurrentHashMap<String, WsCtrl> webSocketMap = new ConcurrentHashMap<>();
	
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		webSocketMap.put(session.getId(), this);
		sendMessage("1");
	}

    @OnClose
    public void onClose(){
    	webSocketMap.remove(session.getId());
    	sendMessage("0");
    }	
//	@OnMessage
//	public void onMessage(String message, Session session) {
//		
//	}
		
	public void sendMessage(String message) {
		try {
			this.session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void sendInfo(String msg) {
		for(Entry<String, WsCtrl> entry :webSocketMap.entrySet()) {
			WsCtrl wc = entry.getValue();
			try {
				wc.sendMessage(msg);
			} catch (Exception e) {
			}
		}
	}
}

当预约成功 开启推送

	/**
	 * 添加预约
	 * @param appointTime
	 * @return
	 */
	@RequestMapping(value = "/insertAppointTime", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> insertAppointTime(Date appointmentDay,String appointmentTime,String empId,String userId,String goodId,HttpServletRequest req){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			resultMap=isAppoint(empId,appointmentDay,appointmentTime);
			String isSub = resultMap.get(ResultKey.KEY_SUCC).toString();
			if("false".equals(isSub)) return resultMap;	//判断当前时间是否可预约
			String apponintId=StringUtil.getUuid();
			AppointTime appointTime=new AppointTime(apponintId,userId,empId,goodId,appointmentTime,appointmentDay,1);
			empService.insertAppointTime(appointTime);
			
			resultMap.put(ResultKey.KEY_DATA, appointTime);
			resultMap.put(ResultKey.KEY_SUCC, true);
			resultMap.put(ResultKey.KEY_CODE, ErrorCodeContents.SUCCESS_CODE);
			resultMap.put(ResultKey.KEY_MSG, "预约成功!");
			//服务器消息推送
			Emp emp = empService.queryEmpReport(empId);
			SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
			String day = sm.format(appointmentDay);
			String push = emp.getEmpNum()+emp.getEmpName()+"于"+day+" "+appointmentTime+"有一个新的预约";
			WsCtrl.sendInfo(push);
		} catch (Exception e) {
			logger.error("{}",e);
			resultMap.put(ResultKey.KEY_SUCC, false);
			resultMap.put(ResultKey.KEY_CODE, ErrorCodeContents.FAILUE_CODE);
			resultMap.put(ResultKey.KEY_MSG, "预约失败!");
		}
		return resultMap;
	}

前端js

window.onload= function(){	
	var websocket;
	if ('WebSocket' in window) {
		websocket = new WebSocket(wsPath + "/webServlet");
	} else if ('MozWebSocket' in window) {
		websocket = new MozWebSocket(wsPath + "/webServlet");
	} else {
		websocket = new SockJS(basePath + "/webServlet");
	}
	websocket.onopen = function(event) {
	};
	websocket.onmessage = function(event) {
		var data = event.data;
		console.log( data);
		if(data != 0 && data != 1){
		var dom = "<div id='msg_from_server'>"+
		  			"<i class='iconfont'>&#xe62a;</i>"+data+
		  		  "</div>";
		$(".tempDiv").html(dom);
		}
	};
	websocket.onerror = function(event) {
		console.log("WebSocket:发生错误 ");
	};
	websocket.onclose = function(event) {
	}
}

效果图
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值