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

 

目录
相关文章
|
18小时前
|
监控 网络协议 Java
使用Spring Boot和WebSocket实现实时通信
使用Spring Boot和WebSocket实现实时通信
|
1天前
|
监控 前端开发 网络协议
如何使用Spring Boot实现WebSocket通信
如何使用Spring Boot实现WebSocket通信
|
1天前
|
消息中间件 Java Kafka
Spring Boot与Kafka的集成应用
Spring Boot与Kafka的集成应用
|
1天前
|
Java 数据库连接 数据库
Spring Boot与MyBatis的集成应用
Spring Boot与MyBatis的集成应用
|
1天前
|
XML JSON Java
Spring Boot与Solr的集成应用
Spring Boot与Solr的集成应用
|
1天前
|
Java 机器人 程序员
Spring Boot与Zookeeper的集成应用
Spring Boot与Zookeeper的集成应用
|
1天前
|
搜索推荐 Java 机器人
教程:Spring Boot中集成Elasticsearch的步骤
教程:Spring Boot中集成Elasticsearch的步骤
|
1天前
|
NoSQL Java MongoDB
如何在Spring Boot应用中集成MongoDB数据库
如何在Spring Boot应用中集成MongoDB数据库
|
1天前
|
Java 机器人 程序员
教程:Spring Boot中如何集成GraphQL
教程:Spring Boot中如何集成GraphQL
|
1天前
|
消息中间件 Java Kafka
Spring Boot与Apache Kafka集成的深度指南
Spring Boot与Apache Kafka集成的深度指南