spring(springmvc)整合WebSocket案例(获取请求参数)开发环境(最低版本):spring 4.0+java7+tomcat7.0.47+sockjs
前端页⾯要引⼊:
<script src="cdn.jsdelivr/sockjs/1/sockjs.min.js"></script>
maven依赖:
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
前端js:
var ws = null;
function openWebSocket(){
/
/判断当前浏览器是否⽀持WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://"+window.location.host+"/项⽬名称/visualizationWebSocket.do?type=mall");
} else {
ws = new SockJS(""+window.location.host+"/项⽬名称/sockjs/visualizationWebSocket/info?type=mall");
}
};
//这个事件是接受后端传过来的数据
//根据业务逻辑解析数据
};
};
}
我实现连接后台的⽅式如下:
//页⾯已加载后加载后台数据
$(function (){
$.ajax({
cache:false,
data:"",
type:"post",
url:"",
success:function(data, textStatus){
if(data && data.status === "1"){
//这⾥可以初始化操作
openWebSocket();//websocket连接到后台
if(ws){
setTimeout(function (){
ws.send("");//发送信息到后台,开始有数据跟新就写到前端显⽰
},3000);
}
} else {
alert("操作失败!");
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){}
});
function zeroPadding(num, digit) {
var zero = '';
for(var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
function showDate() {
var date = new Date();
var str = "" + FullYear(),4) + "-";
str += zeroPadding((Month() + 1),2) + "-";
str += Date(),2) + " ";
str += Hours(),2) + ':';
str += Minutes(),2) + ':';
str += Seconds(),2) + '';
return str;
}
setInterval(function () {
$('.data-time').html(showDate)
}, 1000);
});
后端:
webSocket配置
package com.snw.supplyChain.websocket;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.fig.annotation.EnableWebMvc;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.fig.annotation.EnableWebSocket;
import org.springframework.fig.annotation.WebSocketConfigurer;
import org.springframework.fig.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
@EnableWebMvc
public class VisualizationWebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
//这⾥的url要与页⾯的url⼀致
webSocketHandlerRegistry.addHandler(myHandler(),"/visualizationWebSocket.do").addInterceptors(new VisualizationHandshakeInterceptor());
//⾄于这⾥为什么要加info,我遇见的情况是,当我使⽤sockjs来代替websocket时,连接的后⾯会⾃动加上info
webSocketHandlerRegistry.addHandler(myHandler(),"/sockjs/visualizationWebSocket/info").addInterceptors(new VisualizationHandshakeInterceptor()).withSockJS();
}
@Bean
public WebSocketHandler myHandler(){
return new VisualizationWebSocketHandler();
}
}
回话
package com.snw.supplyChain.websocket;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
//回话
public class VisualizationHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
//获取请求参数,⾸先我们要获取HttpServletRequest对象才能获取请求参数;当ServerHttpRequset的层次结构打开后其⼦类可以获取到我们想要的http对象,那么就简单了。 //我这⾥是把获取的请求数据绑定到session的map对象中(attributes)
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
String id = Session().getId();
System.out.println("beforeHandshake: \n"+id);
String type = Parameter("type");
attributes.put("mall",type);
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
System.out.println("After Handshake");
super.afterHandshake(request, response, wsHandler, ex);
}
}
websocket处理器
处理器⾥⾯可以注⼊想要的service
package com.snw.supplyChain.websocket;
import com.del.VisualizationProduct;
import com.snw.supplyChain.service.IVisualizationService;
import net.sf.json.JSONObject;
import org.apachemons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class VisualizationWebSocketHandler extends TextWebSocketHandler {
private static final Map<String,WebSocketSession> sessions = new HashMap<String, WebSocketSession>(); private static final Map<String,Thread> threads = new HashMap<String, Thread>();
private Thread polingVisualization = null;
//⽤户标识
private static final String CLIENT_ID = "sessionId";
@Autowired
private IVisualizationService visualizationService;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("afterConnectionEstablished: \n"+Id());
Object sessionType = Attributes().get("mall");
if(sessionType != null && "mall".equals(sessionType)){
sessions.put(CLIENT_ID,session);
sessions.Id(),session);
}
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
Thread thread = (Id());
if(thread != null){
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
polingVisualization = null;
try {
super.afterConnectionClosed(session, status);
} catch (Exception e) {
}
}
//这⾥是处理前端发送的消息以及返回给前端的数据
//可以从session⾥⾯获取attributes,
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
super.handleTextMessage(session, message);
Thread thread = (Id());
if(thread == null){
System.out.println("handleTextMessage: \n"+Id());
WebSocketSession sessi = (Id());
if(sessi == null){
sessions.Id(),session);
} else {
session = sessi;
}
final WebSocketSession localSession = session;
final TextMessage localMessage = message;
String payload = Payload();
if(StringUtils.isNotBlank(payload)){
String[] split = payload.split("_");
if(StringUtils.isNotBlank(split[2])){
if("mall".equals(split[1])){
final int universalid = Integer.parseInt(split[2]);
//这⾥的Thread可以⽤urrent代替
Thread polingVisualization = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
polingVisualization(localSession, localMessage, universalid);
try {
Thread.sleep(180000);//300000
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
polingVisualization.start();
threads.Id(),polingVisualization);
springmvc常用标签}
}
}
}
}
private VisualizationProduct polingVisualization(WebSocketSession session,
TextMessage message,Integer universalid) throws IOException {
VisualizationProduct visualizationProduct = visualizationService.findInquiryPriceOrderVisualization(universalid);
Map<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put("status","1");
dataMap.put("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
TextMessage returnMessage = new TextMessage(dataStr);
session.sendMessage(returnMessage);
return visualizationProduct;
}
/**
* 给正在发布的商品发送新数据
* @param universalid 发布会ID
* @param sessionId
*/
public void sendNewProductDatas(Integer universalid, String sessionId){
if(universalid != null){
Set<String> keys = sessions.keySet();
for (String key : keys) {
WebSocketSession webSocketSession = (key);
if(webSocketSession != null && webSocketSession.isOpen()){
VisualizationProduct visualizationProduct = visualizationService.findInquiryPriceOrderVisualization(universalid);
Map<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put("status","1");
dataMap.put("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
System.out.println(dataStr);
TextMessage returnMessage = new TextMessage(dataStr);
try {
webSocketSession.sendMessage(returnMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
spring配置⽂件
⽂件标签,根据需要的添加,⽐如:websocket的xmlns和xsi:schemaLocation
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"
xmlns:context="/schema/context"
xmlns:jee="/schema/jee"
xmlns:websocket="/schema/websocket"
xmlns:tx="/schema/tx"
xmlns:aop="/schema/aop" xmlns:mvc="/schema/mvc"
xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd /schema/context /schema/context/spring-context.xsd
/schema/jee /schema/jee/spring-jee.xsd
/schema/aop /schema/aop/spring-aop.xsd
/schema/tx /schema/tx/spring-tx.xsd
/schema/websocket /schema/websocket/spring-websocket.xsd"> <!-- 配置好处理器-->
<bean id="websocketHandler" class="com.snw.supplyChain.websocket.VisualizationWebSocketHandler"/>
<!-- 配置-->
<websocket:handlers>
<websocket:mapping path="/visualizationWebSocket.do" handler="websocketHandler"/><!-- 连接的URL -->
<websocket:handshake-interceptors>
<bean class="com.snw.supplyChain.websocket.VisualizationHandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
欢迎各位⼤神指点其中不⾜哟。
逻辑处理
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论