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+上则不需要。