Spring Boot项目——Spring Boot配置websocket

步骤

  • 引入依赖
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 创建配置
@Configuration
public class WebsocketConfig {

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

}
  • 创建service
@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocketServiceImpl {
    private Session session;

    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userName")String userName) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(userName, session);
        System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocketServiceImpl webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userName, String message) {
        System.out.println("【websocket消息】单点消息:"+message);
        Session session = sessionPool.get(userName);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
    • 注意此处@ServerEndpoint注解的值要和前端通信的接口地址保持一致,否则不能连接通信。
  • Websocket Server 已经搭建完成,客户端已经可以和服务端通信了。服务端 向客户端推送消息 通过 session.getBasicRemote().sendText(message)

测试

  • 代码如下
@RequestMapping("/websocket")
@RestController
public class WebSocketController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WebSocketServiceImpl webSocketService;

    @ResponseBody
    @GetMapping("/sendAllWebSocket")
    public String test() {
        String text="你们好!这是websocket群体发送!";
        webSocketService.sendAllMessage(text);
        return text;
    }

    @GetMapping("/sendOneWebSocket/{userName}")
    public String sendOneWebSocket(@PathVariable("userName") String userName) {
        String text=userName+" 你好! 这是websocket单人发送!";
        webSocketService.sendOneMessage(userName,text);
        return text;
    }
}
    • 通过url测试通信结果,前端可以打印信息
posted @ 2021-07-15 19:46  话·醉月  阅读(1085)  评论(0编辑  收藏  举报