首页 > 其他分享 >springboot和websocket

springboot和websocket

时间:2022-11-04 15:15:25浏览次数:51  
标签:websocket springboot void session import message public

SpringBoot 使用 WebSocket 非常方便,依赖上仅需要添加相应的 Starter 即可。

1.添加 starter 依赖

在maven中添加引用

   <!--websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>1.3.5.RELEASE</version>
        </dependency>

2.添加websocket配置

package com.ckfuture.springcloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
       return new ServerEndpointExporter();
    }
}

3.通信处理类

package com.ckfuture.springcloud.config;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<MyWebSocket> websocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    private Session session;

    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        websocketSet.add(this);
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为:"+getOnlineCount());
        try{
            sendMessage("8888");
        }catch (IOException e){
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        websocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为:"+getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息:"+message);

        for(MyWebSocket item : websocketSet){
            try{
                item.sendMessage(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时候调用的方法
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送消息方法
     * @param message 消息内容
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    public static void sendInfo(String message) throws IOException{
        for(MyWebSocket item : websocketSet){
            try{
                item.sendMessage(message);
            }catch (IOException e){
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        MyWebSocket.onlineCount++;
    }
    public static synchronized void subOnlineCount(){
        MyWebSocket.onlineCount--;
    }

}

 

4.启动程序,利用在线测试工具测试

 

 

 

 

本文引用:https://blog.csdn.net/qq_40618664/article/details/118016408

标签:websocket,springboot,void,session,import,message,public
From: https://www.cnblogs.com/ckfuture/p/16857683.html

相关文章

  • 给她讲最爱的SpringBoot源码
    1Springboot源码环境构建推荐环境:idea:2020.3gradle:版本gradle-6.5.1jdk:1.8注意!idea和gradle的版本有兼容性问题,要注意搭配1.1Springboot源码下载1、从github获......
  • springboot整合项目-商城个人信息修改功能
    个人资料1持久层1.1需要规划sql语句根据用户信息的sql语句updatet_usersetphone=?,email=?,gender=?modified_time=?,modified_user=?whereuid=?2.根......
  • SpringBoot2默认数据源Hikari
    https://github.com/brettwooldridge/HikariCPJMHBenchmarksMicrobenchmarkswerecreatedtoisolateandmeasuretheoverheadofpoolsusingthe JMHmicrobenchm......
  • SpringBoot 数据源测试
    如下代码,这样可以拿到DataSource,可以直接获取Connection,然后可以直接进行jdbc的处理:importcom.alibaba.druid.pool.DruidDataSource;importorg.junit.Test;importor......
  • springboot如何正确使用tomcat连接池
    原文地址:http://blog.champbay.com/2019/03/29/springboot%E5%A6%82%E4%BD%95%E6%AD%A3%E7%A1%AE%E4%BD%BF%E7%94%A8tomcat%E8%BF%9E%E6%8E%A5%E6%B1%A0/ 在springboot......
  • springboot多模块配置nginx
    1.后端有8088、8089两个端口不同的模块2.在nginx里配置地址。监听端口:9001,转发端口:8088、8099#usernobody;worker_processes1;#error_loglogs/error.log;#er......
  • 基于Springboot+Mybatisplus+Vue的在线购物平台管理系统
    基于Springboot+Mybatisplus+Vue的在线购物平台管理系统......
  • websocket协议详解
    概念介绍①单工通信:数据传输只允许在一个方向上传输,只能一方发送数据,另一方接收数据并发送。②半双工:数据传输允许两个方向上的传输,但在同一时间内,只可以有一方发送或接......
  • springboot全局异常处理
    packagecom.casaba.provider.config;importcom.casaba.provider.domain.vo.AjaxResult;importlombok.extern.slf4j.Slf4j;importorg.springframework.web.HttpReq......
  • springboot web 自定义参数验证
    当需要前端必传某些参数的时候,可在代码里面校验,但是这样每一个方法都需要自己写代码验证。我们可以使用spring提供的@Validate1、单一参数验证接口是单一参数写在方......