springboot creates socket

rely

        <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>

Configuration

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

create

Key points

  1. Scan annotation
    2. Server-side annotation, enter the name for connection
    Insert picture description here
  2. Each annotation indicates the life cycle of the socket, such as OnOpen and OnMessage. They are the time hook when connecting and when receiving a message. Use session.getBasicRemote().sendText() to send a message to the client
package com.learn.testwebsocket.socket;

import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint("/test")
public class TestSocket {
    
    
    @OnOpen
    public Object get(Session session) {
    
    
        System.out.println("连上了");
        try {
    
    
            session.getBasicRemote().sendText("你好,你已经连接上了");
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return "ok";
    }

    @OnMessage
    public void getMessage(String msg) {
    
    
        System.out.println(msg);
    }
}

Guess you like

Origin blog.csdn.net/qq_41948178/article/details/108601514