springboot中使用websocket

1. 引入maven
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置类
@EnableWebSocket
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
3.消息功能模块

由于在该类中无法使用注解引入spring类,所以使用spring的工具类引入bean.

@Slf4j
@Component
@ServerEndpoint("/wbs/{userId}")
public class ChatSocketMessage {

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
     */
    private static ConcurrentHashMap<Integer, Session> webSocketMap = new ConcurrentHashMap<>();

    @OnMessage
    public void handleMessage(@PathParam("userId") Integer userId, String msg) {
        log.info("socket sendMsg ,userId={},msg={}", userId, msg);
        try {
            ChatMessageVo message = JSON.parseObject(msg, ChatMessageVo.class);
            SpringContextHolder.getBean(ChatMessageService.class).saveMessage(message);
        } catch (Exception e) {
            log.error("socket sendMsg error ,userId={},msg={},ex:{}", userId, msg, e);
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        webSocketMap.put(userId, session);
        onlineCount.addAndGet(1);
        log.info("socket create,userId={}", userId);
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") Integer userId) {
        webSocketMap.remove(userId);
        log.info("socket close,userId={}", userId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误,{}", error);
    }

    public void sendMessage(Integer userId, Integer contactId, String message) {
        try {
            Session session = this.webSocketMap.get(userId);
            if (Objects.nonNull(session)) {
                session.getBasicRemote().sendText(message);
            } else {
                SpringContextHolder.getBean(ChatUserService.class).updateUnread(userId, contactId);
            }
        } catch (IOException e) {
            log.error("sendMessage ex:{}", e);
        }
    }

}

spring 工具类:

@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
4. 前端代码
<script type="text/javascript">
    var websocket = null;

    // 判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        // 为了方便测试,故将链接写死
        websocket = new WebSocket("ws://localhost:8088/wbs/1");
    } else{
        alert('Not support websocket')
    }

    // 连接发生错误的回调方法
    websocket.onerror = function(){
        console.log("发生错误");
    };

    // 连接成功建立的回调方法
    websocket.onopen = function(event){
        console.log("打开连接");
    }

    // 接收到消息的回调方法
    websocket.onmessage = function(event){
        console.log(event.data)
    }

    // 连接关闭的回调方法
    websocket.onclose = function(){
        console.log("关闭连接")
    }

    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
    window.onbeforeunload = function(){
        websocket.close();
    }

    // 关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    // 发送消息
    function send(){
        websocket.send(message);
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值