WebSocket和Servlet3.0服务器消息推送技术

2023-12-23 01:08

本文主要是介绍WebSocket和Servlet3.0服务器消息推送技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近研究了两种服务器消息推送技术,一种是WebSocket技术,一种是基于Servlet3.0实现的服务器异步消息推送技术,具体实现如下:

1. WebSocket(聊天室)

WebSocket客户端连接类(javaee-api-7.0.jar)
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;/*** @ServerEndpoint 功能主要是将CharRoomServer 定义为websocket服务器端*/
@ServerEndpoint("/ws/charRoomServer")
public class CharRoomServer {// 会话,主要用于向客户端发送数据private Session session;public Session getSession() {return session;}/*** websocket连接* @param session*/@OnOpenpublic void onOpen(Session session){this.session = session;SessionManager.add(this);     }/*** websocket断开*/@OnClosepublic void onClose(){SessionManage.remove(this);}/*** websocket消息* @param message* @param session*/@OnMessagepublic void onMessage(String message, Session session) {Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String messageFormat = "{\"date\":\"%s\",\"name\":\"%s\",\"content\":\"%s\"}";String msg = String.format(messageFormat, sdf.format(date),"客户端" + session.getId(), message);// 广播SessionManage.broadCast(msg);}/*** websocket错误* @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error){error.printStackTrace();}/*** 广播消息方法* @param message* @throws IOException*/public void sendMessage(String message) throws IOException{this.session.getBasicRemote().sendText(message);}}
SessionManage类
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;public class SessionManage {private static Collection<CharRoomServer> charRoomServers = Collections.synchronizedCollection(new ArrayList<CharRoomServer>());/*** 广播* @param msg*/public static void broadCast(String msg){for (CharRoomServer charRoomServer : charRoomServers) {try {charRoomServer.sendMessage(msg);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*** 新增客户端服务器* @param charRoomServer*/public static void add(CharRoomServer charRoomServer){// 使用时间构造登录信息Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String messageFormat = "{\"date\":\"%s\",\"name\":\"系统\",\"content\":\"%s\"}";String content = "欢迎客户端" + charRoomServer.getSession().getId();String message = String.format(messageFormat, sdf.format(date), content);// 广播broadCast(message);// 加入服务组charRoomServers.add(charRoomServer);}/*** 客户端服务器退出* @param charRoomServer*/public static void remove(CharRoomServer charRoomServer){// 客户端服务器退出charRoomServers.remove(charRoomServer);// 使用时间构造退出信息Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String messageFormat = "{\"date\":\"%s\",\"name\":\"系统\",\"content\":\"%s\"}";String name = "客户端" + charRoomServer.getSession().getId();String message = String.format(messageFormat, sdf.format(date), name + "已退出");// 广播broadCast(message);}}

2. Servlet3.0(SpringBoot:DeferredResult)

Application 入口类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication
@EnableAsync
@EnableScheduling
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
AsyncController异步控制器
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;/*** 异步控制器*/
@RequestMapping("/async")
@RestController
public class AsyncController {private DeferredResult<String> deferredResult;@RequestMapping("/getDeferredResult")public DeferredResult<String> getDeferredResult() {deferredResult = new DeferredResult<String>();return deferredResult;}/*** 每2秒执行一次*/@Scheduled(fixedDelay = 2000)public void refreshDeferredResult() {if (deferredResult != null) {String result = "getDeferredResult:" + System.currentTimeMillis();deferredResult.setResult(result);}}@RequestMapping("/getResult")public String getResult() {return "getResult";}
}
前端页面关键js代码
function getDeferredResult() {$.ajax({url:"/async/getDeferredResult",type:"post",success:function(data){$("table").html(data);getDeferredResult();}});
}
getDeferredResult();
pom文件配置
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example.async</groupId><artifactId>async</artifactId><version>0.0.1-SNAPSHOT</version><!-- 编码和版本 --><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version></properties><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.3.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
</project>

这篇关于WebSocket和Servlet3.0服务器消息推送技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/526177

相关文章

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

Linux搭建ftp服务器的步骤

《Linux搭建ftp服务器的步骤》本文给大家分享Linux搭建ftp服务器的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录ftp搭建1:下载vsftpd工具2:下载客户端工具3:进入配置文件目录vsftpd.conf配置文件4:

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

Python中高级文本模式匹配与查找技术指南

《Python中高级文本模式匹配与查找技术指南》文本处理是编程世界的永恒主题,而模式匹配则是文本处理的基石,本文将深度剖析PythonCookbook中的核心匹配技术,并结合实际工程案例展示其应用,希... 目录引言一、基础工具:字符串方法与序列匹配二、正则表达式:模式匹配的瑞士军刀2.1 re模块核心AP

Linux查询服务器 IP 地址的命令详解

《Linux查询服务器IP地址的命令详解》在服务器管理和网络运维中,快速准确地获取服务器的IP地址是一项基本但至关重要的技能,下面我们来看看Linux中查询服务器IP的相关命令使用吧... 目录一、hostname 命令:简单高效的 IP 查询工具命令详解实际应用技巧注意事项二、ip 命令:新一代网络配置全

Python开发简易网络服务器的示例详解(新手入门)

《Python开发简易网络服务器的示例详解(新手入门)》网络服务器是互联网基础设施的核心组件,它本质上是一个持续运行的程序,负责监听特定端口,本文将使用Python开发一个简单的网络服务器,感兴趣的小... 目录网络服务器基础概念python内置服务器模块1. HTTP服务器模块2. Socket服务器模块

Linux查询服务器系统版本号的多种方法

《Linux查询服务器系统版本号的多种方法》在Linux系统管理和维护工作中,了解当前操作系统的版本信息是最基础也是最重要的操作之一,系统版本不仅关系到软件兼容性、安全更新策略,还直接影响到故障排查和... 目录一、引言:系统版本查询的重要性二、基础命令解析:cat /etc/Centos-release详

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

通过配置nginx访问服务器静态资源的过程

《通过配置nginx访问服务器静态资源的过程》文章介绍了图片存储路径设置、Nginx服务器配置及通过http://192.168.206.170:8007/a.png访问图片的方法,涵盖图片管理与服务... 目录1.图片存储路径2.nginx配置3.访问图片方式总结1.图片存储路径2.nginx配置

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We