WebSocket是一种在单个TCP连接上进行全双工通信的协议,旨在改进客户端和服务器之间的实时通信。以下是关于WebSocket的详细介绍:
WebSocket特别适合需要连续数据交换的服务,如网络游戏、实时交易系统、在线聊天应用、实时协作编辑、实时数据展示、在线游戏、实时地图应用、在线投票系统、实时监控系统以及实时消息推送等。
WebSocket的通信以帧为单位进行,帧的结构包括RSV1、RSV2、RSV3(默认为0,仅当使用extension扩展时,有扩展决定其值)、opcode(帧的类型)、FIN(表示消息的结尾)以及消息长度等内容。
下面是一般项目的常用依赖:
- <dependencies>
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.12version>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>fastjsonartifactId>
- <version>2.0.25version>
- dependency>
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-lang3artifactId>
- <version>3.14.0version>
- dependency>
- <dependency>
- <groupId>com.auth0groupId>
- <artifactId>java-jwtartifactId>
- <version>4.3.0version>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-websocketartifactId>
- dependency>
- <dependency>
- <groupId>org.dom4jgroupId>
- <artifactId>dom4jartifactId>
- <version>2.1.3version>
- dependency>
-
- <dependency>
- <groupId>cn.hutoolgroupId>
- <artifactId>hutool-allartifactId>
- <version>5.8.10version>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-web-servicesartifactId>
- dependency>
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starterartifactId>
- <version>3.0.3version>
- dependency>
-
- <dependency>
- <groupId>com.mysqlgroupId>
- <artifactId>mysql-connector-jartifactId>
- <scope>runtimescope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.mybatis.spring.bootgroupId>
- <artifactId>mybatis-spring-boot-starter-testartifactId>
- <version>3.0.3version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>org.assertjgroupId>
- <artifactId>assertj-coreartifactId>
- dependency>
- dependencies>
GetHttpSession:
- package com.example.cqcrhouduan.config;
-
- import jakarta.servlet.http.HttpSession;
- import jakarta.websocket.HandshakeResponse;
- import jakarta.websocket.server.HandshakeRequest;
- import jakarta.websocket.server.ServerEndpointConfig;
-
- public class GetHttpSession extends ServerEndpointConfig.Configurator {
- @Override
- public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response){
- // 获取httpSession对象
- HttpSession httpSession = (HttpSession) request.getHttpSession();
- // 将httpSession保存起来
- sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
- }
- }
WebsocketConfig:
- package com.example.cqcrhouduan.config;
-
- import jakarta.websocket.server.ServerEndpoint;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.socket.server.standard.ServerEndpointExporter;
-
- @Configuration
- public class WebsocketConfig {
- @Bean
- public ServerEndpointExporter serverEndpointExporter(){
- return new ServerEndpointExporter();
- }
- }
Message:
- package com.example.cqcrhouduan.pojo;
-
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class Message {
- private String toName;
- private String message;
- }
MessageUtil:
- package com.example.cqcrhouduan.pojo;
-
- import com.alibaba.fastjson.JSON;
-
- public class MessageUtil {
- public static String getMessage(boolean isSystemMessage,String fromName,Object message){
- ResultMessage result = new ResultMessage();
- result.setSystem(isSystemMessage);
- result.setMessage(message);
- if(fromName != null){
- result.setFormName(fromName);
- }
- return JSON.toJSONString(result);
- }
- }
ChatEndPoint:
- package com.example.cqcrhouduan.pojo;
-
- import com.alibaba.fastjson.JSON;
- import com.example.cqcrhouduan.config.GetHttpSession;
- import jakarta.servlet.http.HttpSession;
- import jakarta.websocket.*;
- import jakarta.websocket.server.ServerEndpoint;
- import org.springframework.stereotype.Component;
-
- import java.util.Map;
- import java.util.Set;
- import java.util.concurrent.ConcurrentHashMap;
-
- @ServerEndpoint(value = "/chat",configurator = GetHttpSession.class)
- @Component
- public class ChatEndPoint {
-
- private static final Map
onlineUser = new ConcurrentHashMap<>(); -
- private HttpSession httpSession;
- @OnOpen
- public void onOpen(Session session, EndpointConfig config){
- this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
- String user = (String) this.httpSession.getAttribute("user");
- // 1、将session进行保存
- onlineUser.put(user,session);
- // 2、广播消息,将所有登录的用户推送给所有的用户
- String message = MessageUtil.getMessage(true,null,getFriends());
- broadcastAllUser(message);
- }
- private void broadcastAllUser(String Message){
- try{
- // 遍历map集合
- Set
> entries = onlineUser.entrySet(); - for(Map.Entry
entry : entries){ - // 获取所有用户对应的session对象
- Session session = entry.getValue();
- session.getBasicRemote().sendText(Message);
- }
- }catch (Exception e){
- // 记录日志等等
- }
-
- }
- public Set getFriends(){
- Set
set = onlineUser.keySet(); - return set;
- }
-
-
- @OnMessage
- public void opMessage(String message){
- try{
- // 将消息推送给指定的用户:
- Message msg = JSON.parseObject(message,Message.class);
- //获取 消息接收方的名称
- String toNmae = msg.getToName();
- String mes = msg.getMessage();
- Session session = onlineUser.get(toNmae);
- String user = (String) this.httpSession.getAttribute("user");
- String mess = MessageUtil.getMessage(false,user,mes);
- session.getBasicRemote().sendText(mess);
- }catch (Exception e){
- // log
- }
-
-
-
- }
-
-
-
- @OnClose
- public void onClose(Session session){
- String user = (String) this.httpSession.getAttribute("user");
- // 1.从onlinesUser中剔除当前用户
- onlineUser.remove(user);
- // 2.通知其它所有的用户
- String message = MessageUtil.getMessage(true,null,getFriends());
- broadcastAllUser(message);
- }
- }
ResultMessage:
- package com.example.cqcrhouduan.pojo;
-
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
-
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- public class ResultMessage {
- private boolean System;
- private String formName;
- private Object Message;
- }
至此关于Socket利用session来获取信息的后端类的配置就全部完成了,后面将会继续提供前端的配置方法。<( ̄︶ ̄)>!