使用spring4实现websocket连接

原创 2018-02-05 12:08 阅读(2683)次

之前我们都是用tomcat的jar包去实现websocket,因为tomcat7和8实现的代码不一样,升级完后7的代码无法在8下报错。听说spring4实现了websocket,于是我今天就研究了下。我是在我原本的spring项目里加入的websocket,其他spring配置就不一一列举了,我的spring用的是4.0.6,tomcat8,jdk1.8,websocket相关具体实现如下:

maven加入:

                <dependency>  
		   <groupId>org.springframework</groupId>  
		   <artifactId>spring-websocket</artifactId>  
		   <version>4.0.1.RELEASE</version>  
		</dependency>  
		<dependency>  
		   <groupId>org.springframework</groupId>  
		   <artifactId>spring-messaging</artifactId>  
		   <version>4.0.1.RELEASE</version>  
		</dependency>  


新增一份spring-websocket.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
	http://www.springframework.org/schema/beans/spring-beans.xsd  
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd
	">
    
    <bean id="websocketHandler" class="com.solr.websocket.WebsocketHandler"/>  
  
	<websocket:handlers>  
	    <websocket:mapping path="/websocket" handler="websocketHandler"/>  
	    <websocket:handshake-interceptors>  
	    <bean class="com.solr.websocket.HandshakeInterceptor"/>  
	    </websocket:handshake-interceptors>  
	</websocket:handlers>
	 
</beans>


配置文件里有两个类要自己实现如下:

WebsocketHandler.java

package com.solr.websocket;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class WebsocketHandler extends TextWebSocketHandler {

     @Override  
     protected void handleTextMessage(WebSocketSession session,  
            TextMessage message) throws Exception {//后端接收前端websocket.send的消息  
        super.handleTextMessage(session, message);  
        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");  
        session.sendMessage(returnMessage);  
     } 
}

HandshakeInterceptor.java

package com.solr.websocket;

import java.util.Map;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

	@Override  
    public boolean beforeHandshake(ServerHttpRequest request,  
            ServerHttpResponse response, WebSocketHandler wsHandler,  
            Map<String, Object> attributes) throws Exception {  
        System.out.println("Before Handshake");  
        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了:ws://127.0.0.1:8090/test/websocket

所以还需要前端用js连看看:

var ws = new WebSocket("ws://127.0.0.1:8090/test/websocket");
alert();
ws.onopen = function()
{  console.log("open");
  ws.send("message123");
};
ws.onmessage = function(evt){
  console.log(evt.data)
};
ws.onclose = function(evt){
  console.log("WebSocketClosed!");
};
ws.onerror = function(evt){
  console.log("WebSocketError!");

};

这样项目加入websocket支持就实现了!

注意:如果项目里有用到springMVC,需要将spring-websocket.xml文件里的配置,全部搬到springMVC的配置文件spring-mvc.xml里,也就是两个文件合并成一样文件,这样在web.xml中申明springmvc时,才能一并注册websocket的path到springmvc里,否则会报错:

 WARN : No mapping found for HTTP request with URI [/websocket] in DispatcherServlet with name 'springMVC' 

如果要应用到实际项目中,可查看我的一篇文章使用spring4实现websocket连接(二)