赞
踩
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
package com.example.nettyws.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @author yanshuoshi */ @Configuration public class WebsocketConfiguration { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
package com.example.nettyws.websocket; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint("/ws/{arg}") @Component public class MyWebSocket1 { private static ConcurrentHashMap<String, Set<Session>> rooms = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("arg") String arg) { //查询当前动作 if (!rooms.containsKey(arg)) { // 创建房间不存在时,创建房间 Set<Session> room = new HashSet<>(); // 添加用户 room.add(session); rooms.put(arg, room); } else { // 房间已存在,直接添加用户到相应的房间 rooms.get(arg).add(session); } System.out.println("当前共:" + rooms.size() + "个房间!"); } @OnClose public void onClose(Session session,@PathParam("arg") String arg) throws IOException { System.out.println("one connection closed"); rooms.get(arg).remove(session); } @OnError public void onError(Session session, Throwable throwable) { throwable.printStackTrace(); } @OnMessage public void onMessage(Session session, String message,@PathParam("arg") String arg) { System.out.println("接收到数据: " + message); if(message != null && "success".equals(message)){ try { session.getBasicRemote().sendText(message); } catch (IOException ioException) { ioException.printStackTrace(); } return; } // message等于空说明此次连接是为首次连接操作 if (message != null) { for (Session session1 : rooms.get(arg)) { try { session1.getBasicRemote().sendText(message); } catch (IOException ioException) { ioException.printStackTrace(); } } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。