websocket 简易demo

发布时间 2023-10-17 10:01:43作者: budingbuting

websocket简易demo

网上找的然后写的demo

还有一种写法,跟这种写法不同,先记录这一种

引入依赖

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

新建配置类

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

消息处理类

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

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("新连接. . . . . . .");
        try {
            sendMessage("已连接到服务器");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("断开连接. . . . . . .");
    }

    @OnMessage
    public void OnMessage(String message, Session session) {
        System.out.println("收到客户端消息:" + message);
        try {
            sendMessage("收到你的消息 : " + message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

}

启动项目,默认8080端口

postman new-> WebSocket

连接 ws://localhost:8080/websocket

填写Message ,点击发送,收到回复