TGAM-springboot入门练手项目

此项目是个人参与工作室的一个项目,分为硬件、IOS、WEB、后端、数据分析等几大部分,具有实际商用价值。而我虽然只是在其中打杂,写的后端也不够好,但是我会努力地将这系列文章写清楚、详细,若有什么疑问,欢迎QQ:674619459和我交流。另外你的点赞、收藏便是对我最大的鼓励!!
GITHUB:https://github.com/lyf712/TGAM-SpringBoot-Vue-Demo>
简单介绍:https://blog.csdn.net/qq_44654974/article/details/112990344

开发篇
-----基础篇
springboot基本使用
篇1 Springboot学习入门之基本框架搭建和相应准备工作

springboot实现基本功能
篇2 Springboot整合mybatis实现简单登录功能
篇3 Springboot调用阿里云SDK短信服务
篇4 Springboot+mybatis实现简单地增删改查-用户管理
篇5 Springboot结合Redis实现数据分控制位上传
篇6 Springboot 定时任务做超时检验
篇7 Springboot 整合websocket实现后端推送,数据同步

springboot实现安全管理
篇1 采用jwt实现权限管理(一)
篇2 采用jwt+shiro实现权限管理(二)
篇3 采用对称和非对称算法进行数据加密传输

-----提升篇
篇1 websocket进行长连接传输数据
篇2 NGINX+tomcat集群
篇3 初识多线程并发编程
篇4 初识netty

部署篇

篇1 springboot部署阿里云Tomcat
篇2 springboot+Vue部署阿里云Tomcat并使用NGINX反向代理
篇3 springboot+Vue部署阿里云Tomcat并使用NGINX反向代理



前言

参考文章:

springboot+websocket,包括netty,很详细


一、WebSocket是什么?

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

1.为什么需要Websocket?

(1)长连接 (2)双工通信

WebSocket协议基于TCP协议实现,包含初始的握手过程,以及后续的多次数据帧双向传输过程。其目的是在WebSocket应用和WebSocket服务器进行频繁双向通信时,可以使服务器避免打开多个HTTP连接进行工作来节约资源,提高了工作效率和资源利用率。

具体优缺点(包括和http的对比)参考:此博文

2.实现原理

参考此博文

二、JWT使用步骤

1.引入依赖

pom.xml加入

 
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

2.后端配置

(1)配置注入ServerEndpointExporter

@Configuration
public class WebSocketConfig {
    //S
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

(2) 配置WebSocketServer

/**
 *
 * WS协议的controller相当于
 * 参考博文:https://blog.csdn.net/moshowgame/article/details/80275084
 *
 * userId <==> username
 */
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {

    static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) { // 注解回忆: @PathParam 获取路径上的参数(对应上面)

        this.session = session;
        this.userId=userId;

        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        logger.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            logger.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        logger.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("用户消息:"+userId+",报文:"+message);

        //可以群发消息
        //消息保存到数据库、redis


        if(StringUtils.isNotBlank(message)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSONObject.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }else{
                    logger.error("请求的userId:"+toUserId+"不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }


    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /*
    推送JSONObject,无需直接在下一个函数一起发送即可
     */
//    public void sendData(JSONObject res) throws IOException, EncodeException {
//        this.session.getBasicRemote().sendObject(res);
//    }

    /**
     * 自定义userId,在前端(APP 另外一个客户)controller 发送数据()处调用
     * 调用的前提:
     * (1)APP正在发送数据
     * (2)web端确定建立连接
     *
     * (3)如何转发推送??
     * a.APP正在调用的接口处调用此方法(对应示例中的controller推送新消息)
     * b.但是controller的调用条件应该为前端确定同步数据展示,所以此 controller应该设立一个阀门控制
     *
     * @param userId
     */
    public static void sendRecordData(JSONObject transportData,String userId) throws IOException, EncodeException { //转发数据
        /*data处理可以单独写一个函数*/
        // 用户不只一个,在webSocketMap中获取userId,该用户的session,将其发送给他
        /*需要判断是否在线吗? 不需要?因为controller中已经进行判断保证前端打开socket以及userId合法*/
        webSocketMap.get(userId).session.getBasicRemote().sendObject(transportData);

    }


    /**
     * 发送自定义消息(后端推送到前端)
     * */

    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {

        logger.info("发送消息到:"+userId+",报文:"+message);
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            logger.error("用户"+userId+",不在线!");
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

(3)在controller内中进行调用WebsocketServer的发送信息函数(sendInfo,自己根据需要去写),即可推送给已和连接的用户信息。
先给一个场景:
APP传输数据到后端,这时web端进行登录查看,提醒正在记录数据是否同步,若同步则将APP上传记录的数据从controller(APP正在请求上传数据的API)内中调用此函数转发到WEB端。。

3.前端配置

Vue版本(具体参考前言的博文):

 openSocket() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
        //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
        var socketUrl =
          "http://localhost:8083/tgam_service/websocket/" + "Tom22";
        socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
        console.log(socketUrl);
        if (this.socket != null) {
          this.socket.close();
          this.socket = null;
        }
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket.onopen = function() {
          console.log("websocket已打开");
          //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        this.socket.onmessage = function(msg) {
          console.log(msg);
          //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        // this.socket.onclose = function() {
        //   console.log("websocket已关闭");
        // };
        // //发生了错误事件
        // this.socket.onerror = function() {
        //   console.log("websocket发生了错误");
        // };
      }
    },


4.测试

(1)简单的测试方法,使用一个定时器,定时调用推送到指定用户,先不管controller(相当于一个中转站)的推送。


@Component
@EnableScheduling
public class PushToWeb {

    int count=0;

    /*测试向前推送消息*/
    @Bean
   @Scheduled(fixedRate = 3000)
    void test1() throws IOException {
        count++;
        WebSocketServer.sendInfo("第"+count+"次推送给您!","Tom22");
    }

}

效果如下

在这里插入图片描述

(2)个人项目检查推送
打开两个浏览器,一个充当正在记录数据的APP,一个充当查看的PC端。
当APP这边点击开始,则向后端的记录数据controller进行请求,进入controller之后需要进行判断是否转发(采用redis或者属性标注位等方法标记,当前端确定需要同步时,则改变此标注位,那么后端就调用websocket 的sendInfo向指定的该用户推送消息)
在这里插入图片描述

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐