使用spring4实现websocket连接


本文摘自classinstance.cn。

之前我们都是用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连接(二)》。

相关阅读 >>

spring、springmvc、springboot和springcloud的区别

spring如何获取配置在application.properties文件中属性的值?

使用spring4实现websocket连接

使用spring4实现websocket连接(二)

spring事务管理与查询是否需要事务以及可重复读的问题

更多相关阅读请进入《spring4》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...