首先pom依赖添加如下:
javax.websocket
javax.websocket-api
1.1
provided
org.springframework
spring-messaging
4.3.14.RELEASE
org.springframework
spring-websocket
4.3.14.RELEASE
方法1:新建一个类,添加@ServerEndpoint注解
、
@ServerEndpoint(value = "/ws/message")
public class WebSocketMessage {
private static final Logger logger = LoggerFactory.getLogger(WebSocketMessage.class);
@OnMessage
public void onMessage(String message, Session session) throws IOException,
InterruptedException {
WebSocketManager.getInstance().addSession(id + "_publish", session);
logger.debug("websocket connect publish:" + id + "_publish");
System.out.println("注册websocket连接");
}
@OnOpen
public void onOpen() {
logger.debug("已打开连接。");
System.out.println("打开连接");
}
@OnClose
public void onClose() {
logger.debug("已关闭连接。");
System.out.println("关闭连接");
}
@OnError
public void onError(Throwable e) {
//由于客户端浏览器关闭,就会进入该异常,是正常异常,不需要日志
logger.debug("客户端浏览器关闭,WebSocket写入失败.");
}
}
方法2
1)继承AbstractWebSocketHandler,重写方法
public class MyWebsocketHandler extends AbstractWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("websocket连接建立!");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
WebSocketManager.getInstance().addSession("msg", session);
System.out.println(MessageFormat.format("echo message \"{0}\"", message.getPayload()));
session.sendMessage(message);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
session.close(CloseStatus.SERVER_ERROR);
}
}
2)增加1个拦截器
public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map attributes) throws Exception {
System.out.println("Before Handshake");
if (request instanceof ServletServerHttpRequest) {
}
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
3)增加1个配置类
@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer{
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebsocketHandler(), "/websocket/message").addInterceptors(new SpringWebSocketHandlerInterceptor()).setAllowedOrigins("*");;
}
@Bean
public MyWebsocketHandler myWebsocketHandler() {
return new MyWebsocketHandler();
}
}
4)增加1个对DispatchServlet处理的类
public class WebSocketInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return null;
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class>[] {WebsocketConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
5)增加1个管理session创建,删除的类
public class WebSocketManager {
private Map sessions = null;
private static WebSocketManager manager = null;
private WebSocketManager() {
sessions = new HashMap<>();
}
public static WebSocketManager getInstance() {
if(manager == null) {
manager = new WebSocketManager();
}
return manager;
}
public void addSession(String key, WebSocketSession session) {
sessions.put(key, session);
}
public synchronized void removeSession(String key) throws IOException {
WebSocketSession session = sessions.remove(key);
if (session != null && session.isOpen()) {
session.close();
}
}
public Map getSessions() {
return sessions;
}
public void setSessions(Map sessions) {
this.sessions = sessions;
}
}
6)前端没什么好说的,页面代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
Insert title here