spring4.X websocket问题

本文介绍了一个WebSocket服务器的具体配置方法,包括核心组件如WebSocketConfig、WebSocketHandshakeInterceptor和SystemWebSocketHandler等的实现细节。此外还提供了Spring配置文件及web.xml的配置示例。
摘要由CSDN通过智能技术生成

websocket服务器端

WebSocketConfig.java

package com.platform.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements
		WebSocketConfigurer {

	@Bean
	public SystemWebSocketHandler clientHandler() {
		return new SystemWebSocketHandler();
	}

	@Bean
	public WebSocketHandshakeInterceptor interceptor() {
		return new WebSocketHandshakeInterceptor();
	}

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		// TODO Auto-generated method stub
		registry.addHandler(clientHandler(), "/websocket.do").addInterceptors(
				new WebSocketHandshakeInterceptor());
		System.out.println("registed websocket successfull");
	}

	public void configureDefaultServletHandling(
			DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

}
WebSocketHandshakeInterceptor.java

package com.platform.websocket.config;

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 WebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
			WebSocketHandler wsHandler, Exception ex) {
		// TODO Auto-generated method stub
		System.out.println("After Handshake");
		super.afterHandshake(request, response, wsHandler, ex);
	}
	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Before Handshake");
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

}
SystemWebSocketHandler.java

package com.platform.websocket.config;

import java.io.IOException;
import java.util.ArrayList;

import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.platform.util.Constant;
import com.platform.websocket.BootstrapHandlerService;

public class SystemWebSocketHandler implements WebSocketHandler {

	private static final Logger logger;

	private static final ArrayList<WebSocketSession> users;
	
	static {
		users = new ArrayList<>();
		logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	}
	
	@Bean
	public BootstrapHandlerService bootstrapHandlerService() {
		return new BootstrapHandlerService();
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("websocket connection closed......");
        users.remove(session);
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("connect to the websocket success......");
        users.add(session);
        String userName = (String) session.getAttributes().get(Constant.WEBSOCKET_USERNAME);
        if(userName!= null){
        	int count = 0;
            session.sendMessage(new TextMessage(count + ""));
        }
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
			throws Exception {
		// TODO Auto-generated method stub
		 try {
	            StringBuffer sb = new StringBuffer((String) message.getPayload());
	            bootstrapHandlerService().handleMessage(session, sb);
	        } catch (Exception e) {
	            e.printStackTrace();
	            logger.error(e.getMessage());
	        }
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception)
			throws Exception {
		// TODO Auto-generated method stub
		if(session.isOpen()){
            session.close();
        }
		System.out.println("websocket connection closed......");
        logger.debug("websocket connection closed......");
        users.remove(session);
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

}
BootstrapHandlerService.java

package com.platform.websocket;

import java.io.IOException;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
public class BootstrapHandlerService {
	
	public void handleMessage(WebSocketSession session,StringBuffer sb) {
		System.out.println("Message!!!!!!!!!!!!!!!!");
		try {
			session.sendMessage(new TextMessage("Server:connected OK!"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void handleError(WebSocketSession session,Throwable throwable) {
		System.out.println("Error!!!!!!!!!!!!!!!!");
	}
	
	public void connectionClose(WebSocketSession session) {
		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
spring applicationContext.xml配置添加

<!-- WebSocket配置开始 -->
<bean id="websocket" class="com.platform.websocket.config.SystemWebSocketHandler"/>  
<websocket:handlers>  
<span style="white-space:pre">	</span><websocket:mapping path="/websocket.do" handler="websocket"/>  
<span style="white-space:pre">	</span><websocket:handshake-interceptors>  
<span style="white-space:pre">		</span><bean class="com.platform.websocket.config.WebSocketHandshakeInterceptor"/>  
<span style="white-space:pre">	</span></websocket:handshake-interceptors>  
</websocket:handlers>
<!-- WebSocket配置结束 -->
web.xml配置
<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
                classpath:applicationContext.xml
            </param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
开发中遇到的问题:

项目部署在tomcat7.0+上只需spring4.x版本即可,若部署在weblogic上则需spring4.2x,否则会启动会报错。

项目部署在weblogic上时需在web.xml中的servlet里开启servlet异步支持,否则会报The async-support is disabled on this request

<async-supported>true</async-supported>
部署在tomcat7.0+上则不需要。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值