SpringBoot中使用WebSocket的方法

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();
 
    }
 
 
 
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值