001 websocket(评论功能demo)(消息推送)

文章目录

    • ReviewController.java
    • WebSocketConfig.java
    • WebSocketProcess.java
    • ServletInitializer.java
    • WebsocketApplication.java
    • readme
    • index.html
    • application.yaml
    • pom.xml

ReviewController.java


package com.example.controller;

import com.example.websocket.WebSocketProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.time.LocalDateTime;

@RestController
@RequestMapping("review")
public class ReviewController {
    @Autowired
    private WebSocketProcess websocketProcess;

    @GetMapping("save/{clientID}")
    public String saveReview(@PathVariable("clientID") Integer clientID)  {
        Integer replyUserId = 90;// katy
        String replyUsername ="Katy";

        String reviewText = "展览的介绍非常不错,快去看吧!!!";

        String message ="用户"+replyUsername +" 在"+ LocalDateTime.now() +" 回复了您的评论,评论内容是" +reviewText;

        websocketProcess.sendMsg(clientID,message);
        return "successfully";

    }
}


WebSocketConfig.java


package com.example.websocket;

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();
    }
}


WebSocketProcess.java


package com.example.websocket;




/**
 * 该类封装了 客户端与服务器端的Websocket 通讯的
 *  (1) 连接对象的管理   ConcurrentHashMap<Long, WebSocketProcess>
 *  (2) 事件监听      @OnOpen ,  @OnMessage,  @OnClose , @OnError
 *  (3) 服务器向 (所有/单个)客户端 发送消息
 */




//这个代码示例展示了一个简单的WebSocket服务实现,它依赖于Java WebSocket API和Spring框架的一些特性。接下来,我会详细解释为什么这个服务能够实现其功能,特别是@OnOpen、@OnMessage、@OnClose和@OnError这些注解的作用。
//
//WebSocket基本原理
//WebSocket是一种网络通信协议,允许服务器与客户端之间建立持久的连接,并进行全双工通信。这意味着服务器和客户端可以同时发送和接收消息,而不需要像传统的HTTP请求那样,每次通信都需要重新建立连接。
//
//注解解释
//@OnOpen
//
//当一个WebSocket连接成功建立时,@OnOpen注解的方法会被调用。在这个方法中,通常会执行一些初始化操作,比如保存这个连接的信息,以便后续使用。
//在示例中,@OnOpen方法将新的WebSocket连接(即WebSocketProcess对象自身,因为它实现了@ServerEndpoint)存储到ConcurrentHashMap中,以客户端ID为键。这样,服务器就可以跟踪所有活动的WebSocket连接,并能够根据需要将消息发送给特定的客户端。
//@OnMessage
//
//当服务器从WebSocket连接接收到消息时,@OnMessage注解的方法会被调用。这个方法可以处理从客户端发送过来的数据。
//在代码中,@OnMessage方法可能只是简单地接收并打印消息,或者进行其他形式的处理(尽管示例中并未详细展示)。这是WebSocket通信中处理实时数据交换的关键部分。
//@OnClose
//
//当WebSocket连接关闭时(无论是客户端还是服务器发起的关闭),@OnClose注解的方法会被调用。这个方法通常用于清理资源,比如从连接跟踪集合中移除已关闭的连接。
//在代码中,这个方法确保当某个客户端断开连接时,其信息会从ConcurrentHashMap中删除,从而保持连接管理的准确性。
//@OnError
//
//如果在WebSocket通信过程中出现错误,@OnError注解的方法会被调用。这个方法为开发者提供了一个处理异常和错误的机制。
//在示例中,这个方法可能只是简单地打印出错误信息,但在实际应用中,你可能需要执行更复杂的错误处理和恢复逻辑。
//Spring和WebSocket的结合
//Spring框架通过@ServerEndpoint注解和ServerEndpointExporter类为WebSocket提供了强大的支持。@ServerEndpoint注解用于标记一个类作为WebSocket端点,而ServerEndpointExporter则负责在Spring容器中自动注册这些端点。
//
//通过结合Spring的依赖注入和WebSocket的实时通信能力,代码示例实现了一个功能强大的WebSocket服务,能够处理多客户端连接、消息接收和发送等核心功能。
//
//总结
//这个代码示例通过巧妙地结合Java WebSocket API和Spring框架的特性,实现了一个简单但功能完备的WebSocket服务。这个服务能够管理多个并发的WebSocket连接,处理来自客户端的消息,并能够通过REST接口向特定或所有客户端发送消息,展示了WebSocket在实时通信方面的强大能力。






import org.springframework.stereotype.Component;


import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 1. manage client and sever socket object(concurrentHashMap)
 * 2. event trigger :
 *      receive client connect : onopen
 *      receive message from client : onmessage
 *      client socket close :onclose
 *
 * 3. server  send message to client
 */
@Component
@ServerEndpoint(value = "/testWebSocket/{id}")
public class WebSocketProcess {

    private static ConcurrentHashMap<Integer,WebSocketProcess> map = new ConcurrentHashMap();

    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") Integer clientId){
        this.session = session;
        map.put(clientId,this);
        System.out.println("server get a socket from client :"  + clientId);
    }

    //    receive message from client : onmessage
    @OnMessage
    public void onMessage(String message, @PathParam("id") Integer clientId){
        System.out.println("server get message from client id:" + clientId+", and message is :" + message);
    }

    @OnClose
    public void onClose(Session session, @PathParam("id") Integer clientId){
        map.remove(clientId);
    }


    //    server  send message to client
    public  void sendMsg(Integer clientId,String message)  {
        WebSocketProcess socket =  map.get(clientId);
        if(socket!=null){
            if(socket.session.isOpen()){
                try {
                    socket.session.getBasicRemote().sendText(message);
                    System.out.println("server has send message to  client :"+clientId +", and message is:"+ message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println("this client "+clientId +" socket has closed");
            }

        }else{
            System.out.println("this client "+clientId +" socket has exit");
        }
    }


    public  void sendMsg(String message) throws IOException {
        Set<Map.Entry<Integer, WebSocketProcess>> entrySet = map.entrySet();
        for(Map.Entry<Integer, WebSocketProcess> entry: entrySet ){
            Integer clientId = entry.getKey();
            WebSocketProcess socket = entry.getValue();

            if(socket!=null){
                if(socket.session.isOpen()){
                    socket.session.getBasicRemote().sendText(message);
                }else{
                    System.out.println("this client "+clientId +" socket has closed");
                }

            }else{
                System.out.println("this client "+clientId +" socket has exit");
            }
        }




    }

}



ServletInitializer.java



package com.example;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebsocketApplication.class);
    }

}


WebsocketApplication.java



package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WebsocketApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebsocketApplication.class, args);
    }

}


readme


在生产环境中,可能需要更复杂的错误处理和日志记录机制。此外,考虑到安全性,可能还需要实施WebSocket连接的身份验证和授权。



WebSocket服务端:使用WebSocketProcess类来处理WebSocket连接、接收和发送消息。这个类使用了@ServerEndpoint注解来定义WebSocket端点,并通过@OnOpen@OnMessage@OnClose@OnError注解来处理WebSocket事件。

REST控制器:ReviewController类是一个REST控制器,它提供了一个RESTful API(save/{clientID})来模拟用户提交评论,并通过WebSocket向特定客户端发送通知。

配置:WebSocketConfig类配置了ServerEndpointExporter,这是一个Spring Bean,用于注册所有带有@ServerEndpoint注解的类作为WebSocket端点。

前端页面:提供了一个简单的HTML页面,该页面使用JavaScriptWebSocket来与服务器建立连接,并接收服务器发送的消息。
Maven POM文件:定义了项目依赖和构建配置。




WebSocketProcess@Component@ServerEndpoint:这两个注解表明这个类是一个Spring组件和一个WebSocket端点。
ConcurrentHashMap<Integer, WebSocketProcess>:用于管理WebSocket连接。
@OnOpen 方法:当WebSocket连接打开时调用,将连接保存到map中。
@OnMessage 方法:当从客户端接收到消息时调用(但当前实现中未使用消息内容)。
@OnClose 方法:当WebSocket连接关闭时调用,从map中移除连接。
sendMsg 方法:用于向特定客户端或所有客户端发送消息。
ReviewController@RestController@RequestMapping("review"):定义了一个REST控制器,并指定了基础URL路径。
saveReview 方法:提供了一个RESTful API,用于模拟用户提交评论,并通过WebSocket向特定客户端发送通知。
前端页面
JavaScript代码使用new WebSocket("ws://localhost:8080/app/testWebSocket/"+clientID)WebSocket服务端建立连接。
定义了onopen、onmessage和onclose事件处理器来处理WebSocket事件。
Maven POM文件
定义了Spring Boot的父POM和项目的基本信息。
添加了必要的依赖,如spring-boot-starter-websocket、spring-boot-starter-web等。
配置了Maven构建插件。



index.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<h2>Home Page</h2>

<div id="content"></div>

<script>

  $(function (){
    let ws ;
    if('WebSocket' in window){
      console.log("this broswer is  support websocket.")
      let clientID = Math.ceil(Math.random()*100);

      <!-- build webscoket to server  -->
      ws = new WebSocket("ws://localhost:8080/app/testWebSocket/"+clientID);


      ws.onopen = function (){
        $("#content").append("client id= "+clientID +"has connect to server")
      }

      // receive message from server
      ws.onmessage = function (event){
        var message = event.data;
        $("#content").append("<br>");
        $("#content").append("client id= "+clientID +"receive message from server, content is :" + message)
      }

      ws.onclose = function (){
        console.log("client id= "+clientID +"has closed, disconnect to server")
      }



    }else{
      console.log("this browser is not support websocket.")
    }
  })


</script>
</body>
</html>



application.yaml


server:
  servlet:
    context-path: /app





pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>websocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>websocket</name>
    <description>websocket</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>



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





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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>




本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/606017.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

创建和管理数据库

1. 一条数据的存储过程 存储数据是处理数据的第一步.只有正确的把数据存储起来&#xff0c;我们才能进行有效的处理和分析.否则&#xff0c;只能是一团乱麻.在MySQL中&#xff0c;一个完整的数据存储过程一共有四步 : 创建数据库&#xff0c;确认字段&#xff0c;创建数据表&a…

[图解]SysML和EA建模住宅安全系统-01

1 00:00:00,980 --> 00:00:03,100 接下来&#xff0c;我们来看一下案例 2 00:00:04,930 --> 00:00:06,750 我们这次课程的案例 3 00:00:07,090 --> 00:00:13,800 选用了SysML实用指南的书上 4 00:00:13,810 --> 00:00:16,180 第十七章这个案例 5 00:00:16,350 …

RSAC 2024现场:谷歌展望大模型在网络安全领域的前景

人类距离将网络安全的控制权交给生成式AI还有多远&#xff1f; 前情回顾RSAC2024动态 伪造内容鉴别厂商Reality Defender斩获2024 RSAC创新沙盒冠军 RSAC 2024上值得关注的10款网络安全产品 RSAC 2024创新沙盒十强出炉&#xff0c;谁能夺冠&#xff1f; 安全内参5月8日消息…

代码随想录算法训练营第二十一天:树树树

代码随想录算法训练营第二十一天&#xff1a;树树树 ‍ 513.找树左下角的值 力扣题目链接​**&#xff08;打开新窗口&#xff09;** 给定一个二叉树&#xff0c;在树的最后一行找到最左边的值。 示例 1: ​​ 示例 2: ​​ #算法公开课 《代码随想录》算法视频公开课…

跨平台美学!使用DevExpress Reports Office File API时如何管理字体?

DevExpress Office File API是一个专为C#, VB.NET 和 ASP.NET等开发人员提供的非可视化.NET库。有了这个库&#xff0c;不用安装Microsoft Office&#xff0c;就可以完全自动处理Excel、Word等文档。开发人员使用一个非常易于操作的API就可以生成XLS, XLSx, DOC, DOCx, RTF, CS…

鲁大师4月电动两轮车榜:RideyFUN Air智驾系统上线,九号F2z 110智能化再升级

鲁大师4月电动两轮车排行榜数据来源于鲁大师智慧实验室&#xff0c;测评的车型均为市面上主流品牌的主流车型。截止目前&#xff0c;鲁大师智能化电动车测评的车型高达160余台&#xff0c;且还在不断增加和丰富中。 鲁大师电动车智能化测评体系包含车辆的状态采集与管理硬件系统…

android基础-通知

基于第一行android 使用PendingIntent来实现点击通知跳转到另一个活动。 notificationcompat.builder后面可以跟很多的方法&#xff0c;不同方法不同效果&#xff0c;比如加一个音频.setSound(uri) 内置网页 解析json

Spring IoCDI(1)—入门

目录 一、IoC & DI入门 1、Spring是什么 &#xff08;1&#xff09;什么是容器&#xff1f; &#xff08;2&#xff09;什么是IoC&#xff1f; 二、IoC介绍 1、传统程序开发 2、解决方案 3、IoC程序开发 4、IoC优势 三、DI介绍 通过前面的学习&#xff0c;我们知…

开源即时通讯IM框架 MobileIMSDK v6.5 发布

一、更新内容简介 本次更新为次要版本更新&#xff0c;进行了bug修复和优化升级&#xff08;更新历史详见&#xff1a;码云 Release Notes、Github Release Notes&#xff09;。 MobileIMSDK 可能是市面上唯一同时支持 UDPTCPWebSocket 三种协议的同类开源IM框架。轻量级、高…

OpenGVLab/InternVL-Chat-V1-5-Int8

openedai-vision 代码仓库 OpenGVLab/InternVL-Chat-V1-5-Int8 模型文件地址 示 算力平台AutoDL df -h /root/autodl-tmp tar -xvf FileName.tartar -xvf 安装 克隆我们的仓库并跳转到相应目录 2. 创建 conda 环境 cond…

解决Vue devtools插件数据变化不会自动刷新

我们使用devtools插件在监测vuex中表单或自定义组件的数据&#xff0c;发现页面数据发生变化后&#xff0c;但是devtools中还是老数据&#xff0c;必须手动点击devtools刷新才能拿到最新的数据。很烦&#xff01; 解决方案&#xff1a; 打开chrome的设置&#xff0c;向下翻&…

安服仔养成篇——基线检查

基线检查概念理解 先放白嫖来的解释&#xff1a; “安全基线是保持信息系统安全的机密性、完整性、可用性的最小安全控制&#xff0c;是系统的最小安全保证&#xff0c;最基本的安全要求。” 啥意思呢&#xff0c;基线检查其实就是对操作系统、中间件、数据库、网络设备等多…

2024挂耳式耳机怎么选?5款高性价比开放式耳机推荐榜

近年来&#xff0c;开放式耳机受到了越来越多人的关注&#xff0c;特别是对于运动爱好者来说&#xff0c;在运动的过程中&#xff0c;传统的有线耳机不适合户外运动&#xff0c;不仅佩戴不稳&#xff0c;线还容易缠绕&#xff0c;而普通的蓝牙耳机长时间佩戴会感觉耳朵不适。在…

武汉星起航:亚马逊五大促销类型全面解析,打造销售狂欢新篇章

在全球电商领域&#xff0c;亚马逊以其卓越的平台优势和创新的促销策略&#xff0c;为卖家和消费者搭建了一座互通的桥梁。今天&#xff0c;武汉星起航在这里解析亚马逊的五大促销类型&#xff0c;帮助卖家和消费者更好地把握商机&#xff0c;享受购物的乐趣。 一&#xff0e;…

sql 注入 1

当前在email表 security库 查到user表 1、第一步&#xff0c;知道对方goods表有几列&#xff08;email 2 列 good 三列&#xff0c;查的时候列必须得一样才可以查&#xff0c;所以创建个临时表&#xff0c;select 123 &#xff09; 但是你无法知道对方goods表有多少列 用order …

如何在六个月内学会任何一门外语(ted转述)

/仅作学习和参考&#xff0c;勿作他用/ a question : how can you speed up learning? 学得快&#xff0c;减少在学校时间 结果去研究心理学惹 spend less time at school. if you learn really fast , you donot need to go to school at all. school got in the way of …

邮箱Webhook API发送邮件的性能怎么优化?

邮箱Webhook API发送邮件的步骤&#xff1f;如何用邮箱API发信&#xff1f; 随着业务规模的扩大&#xff0c;如何高效地通过邮箱Webhook API发送邮件&#xff0c;成为了许多企业面临的关键问题。下面&#xff0c;AokSend将探讨一些优化邮箱Webhook API发送邮件性能的方法。 邮…

Tomcat端口占用解决方案

Windows操作系统 出现这种情况&#xff1a; Error was Port already in use :40001&#xff1b;nested exception is :java.net.BindException: Address already in use : JVM_Bind; 步骤1&#xff1a;按下winR键&#xff0c;输入cmd 步骤2&#xff1a;输入以下命令 netstat …

基于D1开发板和腾讯云nginx服务器构建家庭视频监控方案

腾讯云服务器使用nginx搭建rtmp服务器 什么是nginx&#xff1f; nginx是一款优秀的反向代理工具&#xff0c;通过nginx可以实现搭建高可用的轻量级web服务器&#xff0c;除此之外&#xff0c;通过Nginx自带的rtmp模块&#xff0c;也可以实现rtmp服务器的搭建。 安装nginx 安装编…

ESD静电问题 | 摄像头空气放电重启

【转自微信公众号&#xff1a;必学大课堂】
最新文章