引入依赖

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
  • 1.
  • 2.
  • 3.

maven依赖pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.

创建websocket代码

@ServerEndpoint("/ws/progress")
@Component
public class MyWebSocket {
    
    private Session session;
    
	@OnOpen
    public void onOpen(){
    }
    
    @OnClose
    public void onClose() {
    }
    
     public Session getSession() {
        return session;
    }
    
    //发送消息
    public static void sendMsg(String message){
        MyWebSocket mySocket = new MyWebSocket();
        mySocket.getSession().getBasicRemote().sendText(message);
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
ServerEndpoint的使用
  1. 注解定义
  • @ServerEndpoint注解用于标识一个类为WebSocket服务端点,该注解必须包含至少一个value参数,用于指定WebSocket服务端点的URI地址。
  • 常用的注解还包括@OnOpen@OnClose@OnMessage@OnError,分别用于处理连接建立、连接关闭、接收消息、发生错误的情况。


@ServerEndpoint("/ws")  
public class WebSocketEndpoint {  
    @OnOpen  
    public void onOpen(Session session) {  
        // 连接建立时的处理逻辑  
    }  

    @OnClose  
    public void onClose(Session session) {  
        // 连接关闭时的处理逻辑  
    }  

    @OnMessage  
    public void onMessage(String message, Session session) {  
        // 收到消息时的处理逻辑  
    }  

    @OnError  
    public void onError(Session session, Throwable throwable) {  
        // 发生错误时的处理逻辑  
    }  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.