springboot集成websocket

简介: springboot集成websocket

一、依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、配置

server:
  port: 6655
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpoint() {
        return new ServerEndpointExporter();
    }
}
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketUtil {
    private static int onlineCount=0;//在线人数
    private static CopyOnWriteArrayList<WebSocketUtil> webSocketSet=new CopyOnWriteArrayList<WebSocketUtil>();//在线用户集合
    private Session session;//与某个客户端的连接会话
    private String currentUser;
 
    @OnOpen
    public void onOpen(@PathParam("token") String token, Session session){
        this.currentUser = token;
        this.session=session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为"+getOnlineCount());
        allCurrentOnline();
    }
 
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        allCurrentOnline();
    }
 
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端的消息:"+message);
        for (WebSocketUtil item:webSocketSet){
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
 
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误!");
        throwable.printStackTrace();
    }
 
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
 
    /**
     * 获取当前所有在线用户名
     */
    public static void allCurrentOnline(){
        for (WebSocketUtil item : webSocketSet) {
            System.out.println(item.currentUser);
        }
    }
 
    /**
     * 发送给指定用户
     */
    public static void sendMessageTo(String message,String token) throws IOException {
        for (WebSocketUtil item : webSocketSet) {
            if(item.currentUser.equals(token)){
                System.out.println("token:"+message);
                item.session.getBasicRemote().sendText(message);
            }
        }
    }
 
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        System.out.println(message);
        for (WebSocketUtil item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }
 
    public static synchronized int getOnlineCount(){
        return onlineCount;
    }
    public static synchronized void addOnlineCount(){
        WebSocketUtil.onlineCount++;
    }
    public static synchronized void subOnlineCount(){
        WebSocketUtil.onlineCount--;
    }
 
}

三、测试

 import com.example.websocketdemo.util.WebSocketUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
 
@RestController
public class MessageController {
    //给指定用户发
    @GetMapping("/sendone/{token}/{message}")
    public String sendmessage(@PathVariable("message") String message,@PathVariable("token") String token) throws IOException {
        WebSocketUtil.sendMessageTo(message,token);
        return "ok";
    }
 
    //这个可以后台群发,所有用户都能看到
    @GetMapping("/sendall/{message}")
    public String sendmessageall(@PathVariable("message") String message) throws IOException {
        WebSocketUtil.sendInfo(message);
        return "ok";
    }
 
}
<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>websocket</title>
    
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               console.log("您的浏览器支持 WebSocket!");
               
               // 打开一个 web socket
               // var ws = new WebSocket("ws://192.168.1.22:48080/admin-api/websocket/1234");
               var ws = new WebSocket("ws://192.168.1.22:6655/websocket/1234");
               ws.onopen = function()
               {
                  // Web Socket 已连接上,使用 send() 方法发送数据
      //             ws.send("发送数据");
                  console.log("与服务器建立连接成功!")
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  console.log("接收数据:" + received_msg)
               };
                
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  alert("连接已关闭..."); 
               };
            }
            
            else
            {
               // 浏览器不支持 WebSocket
               alert("您的浏览器不支持 WebSocket!");
            }
         }
      </script>
        
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>

发送一条消息

http://localhost:6655/sendone/1234/hi

 

相关文章
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
610 0
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
459 0
|
10月前
|
前端开发
SpringBoot2.3.1集成Knife4j接口文档
SpringBoot2.3.1集成Knife4j接口文档
1043 44
|
9月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
554 3
|
9月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
801 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
9月前
|
Java 关系型数据库 MySQL
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
springboot项目集成dolphinscheduler调度器 实现datax数据同步任务
880 2
|
9月前
|
分布式计算 Java 大数据
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
springboot项目集成dolphinscheduler调度器 可拖拽spark任务管理
484 2
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
226 0
|
10月前
|
缓存 安全 Java
Shiro简介及SpringBoot集成Shiro(狂神说视频简易版)
Shiro简介及SpringBoot集成Shiro(狂神说视频简易版)
835 7