SpringBoot整合Websocket实现即时聊天功能

小弟第一次写博客,空闲时间整理出来,望大家互相交流! 如有技术上的漏洞,请海涵!

近期,公司需要新增即时聊天的业务,于是用websocket 整合到Springboot完成业务的实现。

一、我们来简单的介绍下websocket的交互原理:
1.客户端先服务端发起websocket请求;
2.服务端接收到请求之后,把请求响应返回给客户端;
3.客户端与服务端只需要一次握手即可完成交互通道;
如图所示: SpringBoot整合Websocket实现即时聊天功能_第1张图片
二、webscoket支持的协议:基于TCP协议下,http协议和https协议;
http协议 springboot不需要做任何的配置
https协议则需要配置nignx代理,注意证书有效的问题 —在这不做详细说明
三、开始我们的实现java后端的实现
1.添加依赖

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

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-websocket</artifactId>
          <version>${
     spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-messaging</artifactId>
          <version>${
     spring.version}</version>
      </dependency>
      <!-- WebSocket -->
	2.配置config
@ConditionalOnWebApplication
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer {
     
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
     
        return  new ServerEndpointExporter();
    }
    @Bean
    public CustomSpringConfigurator customSpringConfigurator() {
     
        return new CustomSpringConfigurator(); 
    }
    @Override
    protected void configureStompEndpoints(StompEndpointRegistry registry) {
     
        registry.addEndpoint("/websocket").setAllowedOrigins("*")
                .addInterceptors(new HttpSessionHandshakeInterceptor()).withSockJS();
    }
 	public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
     


    private static volatile BeanFactory context;

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
     
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     
        CustomSpringConfigurator.context = applicationContext;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec,
                                HandshakeRequest request, HandshakeResponse response) {
     
        super.modifyHandshake(sec,request,response);
        HttpSession httpSession=(HttpSession) request.getHttpSession();
        if(httpSession!=null){
     
            sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
        }
    }

}
@SpringBootApplication
@EnableCaching
@ComponentScan("com")
@EnableWebSocket
public class Application extends SpringBootServletInitializer {
     
	 static final Logger logger = LoggerFactory.getLogger(Application.class);
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
     
        return application.sources(Application.class);
    }

需要注意的是: @EnableWebSocket 一定要加在启动类上,不然springboot无法对其扫描进行管理;
@SeverEndpoint --将目标类定义成一个websocket服务端,注解对应的值将用于监听用户连接的终端访问地址,客户端可以通过URL来连接到websocket服务端。

四、设计思路:用map<房间id, 用户set>来保存房间对应的用户连接列表,当有用户进入一个房间的时候,就会先检测房间是否存在,如果不存在那就新建一个空的用户set,再加入本身到这个set中,确保不同房间号里的用户session不串通!


/**
 * Create by wushuyu
 * on 2020/4/30 13:24
 * 
*/
@ServerEndpoint(value = "/websocket/{roomName}", configurator = CustomSpringConfigurator.class)
@Component
public class WebSocketRoom {
     
    //连接超时--一天
    private static final long MAX_TIME_OUT = 24*60*60*1000; 
    // key为房间号,value为该房间号的用户session
    private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap<>();
    //将用户的信息存储在一个map集合里
    private static final Map<String, Object> users = new ConcurrentHashMap<>();
	/**
	*{roomName} 使用通用跳转,实现动态获取房间号和用户信息  格式:roomId|xx|xx
	*/
    @OnOpen  
    public void connect(@PathParam("roomName") String roomName, Session session) {
     
        String roomId = roomName.split("[|]")[0];
        String nickname = roomName.split("[|]")[1];
        String loginId = roomName.split("[|]")[2];
         //设置连接超时时间
            session.setMaxIdleTimeout(MAX_TIME_OUT);
        try {
     
           
           //可实现业务逻辑
            }
            // 将session按照房间名来存储,将各个房间的用户隔离
            if (!rooms.containsKey(roomId)) {
     
                // 创建房间不存在时,创建房间
                Set<Session> room = new HashSet<>();
                // 添加用户
                room.add(session);
                rooms.put(roomId, room);
            } else {
      // 房间已存在,直接添加用户到相应的房间               
                if (rooms.values().contains(session)) {
     //如果房间里有此session直接不做操作
                } else {
     //不存在则添加
                    rooms.get(roomId).add(session);
                }
            }
            JSONObject jsonObject = new JSONObject();
            -----
            //根据自身业务情况实现业务
            -----
            users.put(session.getId(), jsonObject);
            //向在线的人发送当前在线的人的列表     -------------可有可无,看业务需求
            List<ChatMessage> userList = new LinkedList<>();
            rooms.get(roomId)
                    .stream()
                    .map(Session::getId)
                    .forEach(s -> {
     
                        ChatMessage chatMessage = new ChatMessage();
                        chatMessage.setDate(new Date());
                        chatMessage.setStatus(1);
                        chatMessage.setChatContent(users.get(s));
                        chatMessage.setMessage("");
                        userList.add(chatMessage);
                    });
//        session.getBasicRemote().sendText(JSON.toJSONString(userList));
            //向房间的所有人群发谁上线了
            ChatMessage chatMessage = new ChatMessage();   ----将聊天信息封装起来。
            chatMessage.setDate(new Date());
            chatMessage.setStatus(1);
            chatMessage.setChatContent(users.get(session.getId()));
            chatMessage.setMessage("");
            broadcast(roomId, JSON.toJSONString(chatMessage));
            broadcast(roomId, JSON.toJSONString(userList));
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    @OnClose
    public void disConnect(@PathParam("roomName") String roomName, Session session) {
     
        String roomId = roomName.split("[|]")[0];
        String loginId = roomName.split("[|]")[2];
        try {
     
            rooms.get(roomId).remove(session);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setDate(new Date());
            chatMessage.setUserName(user.getRealname());
            chatMessage.setStatus(0);
            chatMessage.setChatContent(users.get(session.getId()));
            chatMessage.setMessage("");
            users.remove(session.getId());
            //向在线的人发送当前在线的人的列表  ----可有可无,根据业务要求
            List<ChatMessage> userList = new LinkedList<>();
            rooms.get(roomId)
                    .stream()
                    .map(Session::getId)
                    .forEach(s -> {
     
                        ChatMessage chatMessage1 = new ChatMessage();
                        chatMessage1.setDate(new Date());
                        chatMessage1.setUserName(user.getRealname());
                        chatMessage1.setStatus(1);
                        chatMessage1.setChatContent(users.get(s));
                        chatMessage1.setMessage("");
                        userList.add(chatMessage1);
                    });
            broadcast(roomId, JSON.toJSONString(chatMessage));
            broadcast(roomId, JSON.toJSONString(userList));
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    @OnMessage
    public void receiveMsg( String msg, Session session) {
     
        try {
     
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setUserName(user.getRealname());
                chatMessage.setStatus(2);
                chatMessage.setChatContent(users.get(session.getId()));
                chatMessage.setMessage(msg);
                // 按房间群发消息
                broadcast(roomId, JSON.toJSONString(chatMessage));
            }
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }

    // 按照房间名进行群发消息
    private void broadcast(String roomId, String msg) {
     
        rooms.get(roomId).forEach(s -> {
     
            try {
     
                s.getBasicRemote().sendText(msg);   -----此还有一个getAsyncRemote()   
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        });
    }

    @OnError
    public void onError(Throwable error) {
     
        error.printStackTrace();
    }
}

友情提示:此session是websocket里的session,并非httpsession;

你可能感兴趣的:(websocket,java,spring,boot,websocket)