添加websocket

This commit is contained in:
Cool 2024-07-05 16:28:02 +08:00
parent b70501c750
commit 7d7802acb8
4 changed files with 102 additions and 0 deletions

View File

@ -34,6 +34,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>

View File

@ -0,0 +1,20 @@
package com.example.aitest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/*
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*
* */
// @Profile("!test")
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

View File

@ -0,0 +1,63 @@
package com.example.aitest.controller.websocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@CrossOrigin
@Slf4j
@ServerEndpoint(value = "/danger/get")
@Component
public class WebSocketServer {
private static final List<Session> sessionList = new CopyOnWriteArrayList<>();
@OnOpen
public void onOpen(Session session) throws IOException {
sessionList.add(session);
log.info("有新用户加入聊天,当前在线人数为{}", sessionList.size());
sendAllSession("二级");
}
@OnMessage
public void onMessage(String message) throws IOException {
log.info("webMessage{}",message);
sendAllSession(message);
}
@OnError
public void onError(Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
@OnClose
public void onClose(Session session) {
log.info("有一个用户断开连接了");
sessionList.remove(session);
}
/*
* 发消息给客户端
* */
public void sendAllSession(String message){
try {
for (Session session : sessionList) {
log.info("给客户端发送消息{}", session);
session.getBasicRemote().sendText(message);
}
} catch (Exception e) {
log.error("消息发送失败", e);
}
}
}

View File

@ -0,0 +1,14 @@
package com.example.aitest;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class WebsocketTest {
@Test
public void test() {
System.out.println("Test");
}
}