SpringBoot中使用WebSocket的方法

1.基本概念

所谓WebSocket, 类似于Socket,它的作用是可以让Web应用中的客户端和服务端建立全双工通信。在基于Spring的应用中使用WebSocket一般可以有以下三种方式:

使用Java提供的@ServerEndpoint注解实现
使用Spring提供的低层级WebSocket API实现
使用STOMP消息实现

2.使用Spring提供的低层级WebSocket API实现

概念

Spring 4.0为WebSocket通信提供了支持,包括:

发送和接收消息的低层级API;

发送和接收消息的高级API;

用来发送消息的模板;

支持SockJS,用来解决浏览器端、服务器以及代理不支持WebSocket的问题。

使用步骤
1.添加一个WebSocketHandler

定义一个继承了AbstractWebSocketHandler类的消息处理类,然后自定义对”建立连接“、”接收/发送消息“、”异常情况“等情况进行处理

package cn.zifangsky.samplewebsocket.websocket;
 
 
 
import cn.zifangsky.samplewebsocket.service.EchoService;
 
import org.slf4j.Logger;
 
import org.slf4j.LoggerFactory;
 
import org.springframework.web.socket.CloseStatus;
 
import org.springframework.web.socket.TextMessage;
 
import org.springframework.web.socket.WebSocketSession;
 
import org.springframework.web.socket.handler.TextWebSocketHandler;
 
 
 
import javax.annotation.Resource;
 
import java.text.MessageFormat;
 
 
 
/**
* 通过继承 {@link org.springframework.web.socket.handler.AbstractWebSocketHandler} 的示例
*/
 
public class EchoWebSocketHandler extends TextWebSocketHandler{
 
    private final Logger logger = LoggerFactory.getLogger(getClass());
 
 
 
    @Resource(name = "echoServiceImpl")
 
    private EchoService echoService;
 
 
 
    @Override
 
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
 
        logger.debug("Opened new session in instance " + this);
 
    }
 
 
 
    @Override
 
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
 
        //组装返回的Echo信息
 
        String echoMessage = this.echoService.echo(message.getPayload());
 
        logger.debug(MessageFormat.format("Echo message \"{0}\"", echoMessage));
 
 
 
        session.sendMessage(new TextMessage(echoMessage));
 
    }
 
 
 
    @Override
 
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
 
        session.close(CloseStatus.SERVER_ERROR);
 
        logger.debug("Info: WebSocket connection closed.");
 
    }
 
}
2.WebSocket相关配置
package cn.zifangsky.samplewebsocket.config;
 
 
 
import cn.zifangsky.samplewebsocket.websocket.EchoWebSocketHandler;
 
import org.springframework.context.annotation.Bean;
 
import org.springframework.context.annotation.Configuration;
 
import org.springframework.web.socket.WebSocketHandler;
 
import org.springframework.web.socket.config.annotation.EnableWebSocket;
 
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
 
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
 
 
/**
* WebSocket相关配置
*/
 
@Configuration
 
@EnableWebSocket
 
public class WebSocketConfig implements WebSocketConfigurer{
 
 
 
    @Override
 
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
 
        registry.addHandler(echoWebSocketHandler(), "/echoMessage");
 
        registry.addHandler(echoWebSocketHandler(), "/echoMessage_SockJS").withSockJS();
 
    }
 
 
 
    /**
     * 通过继承 {@link org.springframework.web.socket.handler.AbstractWebSocketHandler} 的示例
     */
 
    @Bean
 
    public WebSocketHandler echoWebSocketHandler(){
 
        return new EchoWebSocketHandler();
 
    }
 
 
 
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐