折腾了将近一天,终于搭建好websocket服务,中间遇到不少的坑,现在记录一下,也供他们参考少走弯路。
开发环境:
spring搭建websocket有两种方式:
1、利用javaee-api以注解的形式搭建,见上一篇博文《spring+tomcat8实现websocket 》
2、利用spring-websocket包搭建,本篇介绍的内容。
注意:这种方式必须注释掉这个,不然会冲突
需要用到的spring包:
其他辅助包:
Java代码:两个类 WebSocketConfig 和 SystemWebSocketHandler
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer{
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(systemWebSocketHandler(),"/webSocketServer");
registry.addHandler(systemWebSocketHandler(),"/webSocketServer/sockjs").setAllowedOrigins("*").withSockJS();
//registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor());
//registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor()).withSockJS();
//registry.addHandler(systemWebSocketHandler(), "/webSocketServer/sockjs").withSockJS();
/*registry.addHandler(systemWebSocketHandler(),"/ws").addInterceptors(new WebSocketHandshakeInterceptor());
registry.addHandler(systemWebSocketHandler(), "/ws/sockjs").addInterceptors(new WebSocketHandshakeInterceptor())
.withSockJS();*/
}
@Bean
public WebSocketHandler systemWebSocketHandler(){
return new SystemWebSocketHandler();
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
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.mspj.frame.core.web.controller.BaseWebControllerImpl;
public class SystemWebSocketHandler implements WebSocketHandler {
private Logger log = LoggerFactory.getLogger(SystemWebSocketHandler.class);
private static final ArrayList users = new ArrayList();;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("ConnectionEstablished");
log.debug("ConnectionEstablished");
users.add(session);
session.sendMessage(new TextMessage("connect"));
session.sendMessage(new TextMessage("new_msg"));
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage> message) throws Exception {
System.out.println("handleMessage" + message.toString());
log.debug("handleMessage" + message.toString());
//sendMessageToUsers();
session.sendMessage(new TextMessage(new Date() + ""));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if(session.isOpen()){
session.close();
}
users.remove(session);
log.debug("handleTransportError" + exception.getMessage());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
users.remove(session);
log.debug("afterConnectionClosed" + closeStatus.getReason());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
/**
* 给所有在线用户发送消息
*
* @param message
*/
public void sendMessageToUsers(TextMessage message) {
for (WebSocketSession user : users) {
try {
if (user.isOpen()) {
user.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)
SockJS transport:
echoendpoint test
echoendpoint test
最后说下几个坑点:
1、html页面访问限制的问题的:403 Forbidden
registry.addHandler(systemWebSocketHandler(),"/webSocketServer/sockjs").setAllowedOrigins("*").withSockJS();
2、web.xml配置需要升级成3.1
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
3、web.xml里面所有过滤器需要加上
如: