(java)websocket服务的两种实现方式

1.基于java注解实现websocket服务器端

1.1需要的类

1.1.1服务终端类

用java注解来监听连接@ServerEndpoint、连接成功@OnOpen、连接失败@OnClose、收到消息等状态@OnMessage

1.1.2配置类

把spring中的ServerEndpointExporter对象注入进来

2.1代码示例

2.1.1 maven配置

<?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.heima</groupId><artifactId>ws-demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.7.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.22</version></dependency><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><version>2.7.14</version></dependency></dependencies></project>

2.1.2 WsServerEndpoint类

package com.heima;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
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.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;/**** 监听websocket地址  /myWs*/
@ServerEndpoint("/myWs")
@Component
@Slf4j
@EnableScheduling
public class WsServerEndpoint {static Map<String,Session> map = new ConcurrentHashMap<String,Session>();/**** 连接建立时执行的操作* @param session*/@OnOpenpublic void onOpen(Session session){map.put(session.getId(),session);log.info("websocket is open");}/**** 收到客户端消息执行的操作* @param text*/@OnMessagepublic String OnMessage(String text){log.info("收到了一条信息"+text);return "已收到你的信息" ;}/**** 连接关闭时执行的操作* @param session*/@OnClosepublic void OnClose(Session session){map.remove(session.getId());log.info("连接关闭时执行的操作");}/**** 向客户端发送信息*/@Scheduled(fixedRate = 2000)public void sendMsg() throws IOException {for (String key : map.keySet()){map.get(key).getBasicRemote().sendText("你好,你好");}}
}

2.1.3 WebSocketConfig

package com.heima;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}}

2.1.3 前端测试代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>wsClient</title>
</head>
<body><script>// 创建websocketlet ws = new WebSocket("ws://localhost:8080/myWs")//向服务器发送hellows.onopen=function (){ws.send("hello")}//监听数据ws://localhost:8080/myWsws.onmessage=function (message){console.log(message.data)}
</script>
</body>
</html>

2.1.4测试结果

2.1.4.1 当打开浏览器时

2.1.4.2 当关闭浏览器时

2.1.4.3 当刷新浏览器的时候

2.基于spring提供的类和接口刷新websocket服务器端

2.1:HttpSessionHandShakeInter 握手拦截器

package com.spring;import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;import java.util.Map;/**** 握手拦截器*/
@Component
@Slf4j
public class MyWsInterceptor extends HttpSessionHandshakeInterceptor {@Overridepublic boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {log.info(request.getRemoteAddress().toString()+"开始握手");return super.beforeHandshake(request, response, wsHandler, attributes);}@Overridepublic void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {log.info(request.getRemoteAddress().toString()+"完成握手");super.afterHandshake(request, response, wsHandler, ex);}
}

2.2  MyWsHandler 主处理程序

sessionbean封装类
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.socket.WebSocketSession;@Data
@AllArgsConstructor
public class SessionBean {private WebSocketSession webSocketSession;private Integer clientId;
}
 主处理程序
package com.spring;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;/**** webSocket 主处理程序*/
@Component
@Slf4j
@EnableScheduling
public class MyWsHandler extends AbstractWebSocketHandler {//map有并发线程问题  所以用ConcurrentHashMapprivate static Map<String, SessionBean> map ;//id有并发问题 所以用Integer的安全类型private static AtomicInteger clientIdMaker;static {map = new ConcurrentHashMap<>();clientIdMaker=new AtomicInteger(0);}//连接建立@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {super.afterConnectionEstablished(session);//将session 进一步封装  id采用的是自增SessionBean sessionBean = new SessionBean(session, clientIdMaker.getAndIncrement());map.put(session.getId(),sessionBean);log.info(map.get(session.getId()).getClientId()+"建立了连接");}//收到消息@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {super.handleTextMessage(session, message);log.info(map.get(session.getId()).getClientId()+":"+message.getPayload());}//传输异常@Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {super.handleTransportError(session, exception);if (session.isOpen()){session.close();}map.remove(session.getId());}//连接关闭@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {super.afterConnectionClosed(session, status);log.info(map.get(session.getId()).getClientId()+"关闭连接");}/**** 向客户端发送信息*/@Scheduled(fixedRate = 2000)public void sendMsg() throws IOException {for (String key : map.keySet()){map.get(key).getWebSocketSession().sendMessage(new TextMessage("hello," +"spring socket"));}}
}

2.3 WebSocketConfigurer 注册拦截器和主处理程序以及监听路径

package com.spring;import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;import javax.annotation.Resource;@Configuration
@EnableWebSocket
public class MyWsConfig implements WebSocketConfigurer {@Resourceprivate MyWsHandler wsHandler;@Resourceprivate MyWsInterceptor wsInterceptor;@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(wsHandler,"/myWs1").addInterceptors(wsInterceptor).setAllowedOriginPatterns("*");}
}

2.4 前端测试

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>wsClient</title>
</head>
<body><script>// 创建websocketlet ws = new WebSocket("ws://localhost:8080/myWs1")//向服务器发送hellows.onopen=function (){ws.send("hello")}//监听数据ws://localhost:8080/myWsws.onmessage=function (message){console.log(message.data)}
</script>
</body>
</html>

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

易图讯科技三维电子沙盘系统

深圳易图讯科技有限公司&#xff08;www.3dgis.top&#xff09;创立于2013年&#xff0c;专注二三维地理信息、三维电子沙盘、电子地图、虚拟现实、大数据、物联网和人工智能技术研发&#xff0c;获得20多项软件著作权和软件检测报告&#xff0c;成功交付并实施了1000多个项目&…

本地电脑hosts强制解析指定IP的方法

网站接入CDN后&#xff0c;很多时候需要本地强制解析回源查看状态&#xff0c;比如查看是不是源服务器故障&#xff0c;网站修改是否正确&#xff0c;网站更新是否及时&#xff0c;故障查看是CDN问题还是源服务器问题&#xff0c;都需要hosts回源。 今天云加速教大家如何本地电…

Python悬置动刚度模拟及复数绘制

Python悬置动刚度模拟及复数绘制 1、复数绘制极坐标图2、动刚度的计算公式3、悬置动刚度的影响因素4、 AVL Excite 悬置动刚度的模拟 1、复数绘制极坐标图 # _*_ coding:UTF-8 _*_import matplotlib.pyplot as plt import numpy as np# 定义复数数组 complexNums [1.5 1.2j,…

SM4-GCM Library代码示例

sm4-gcm加密解密测试代码: fn main() {let key Sm4Key([0u8; 16]);let nonce [0u8; 12];let plaintext b"Hello World!";let ciphertext sm4_gcm::sm4_gcm_encrypt(&key, &nonce, plaintext);println!("Encrypted: {}", hex::encode(&cip…

GDPU JavaWeb 过滤器

再纯净的白开水也过滤不了渣茶。 Servlet登陆页面 引入数据库&#xff0c;创建用户表&#xff0c;包括用户名和密码&#xff1a;客户端通过login.jsp发出登录请求&#xff0c;请求提交到loginServlet处理。如果用户名和密码跟用户表匹配则视为登录成功&#xff0c;跳转到loginS…

MySQL 身份认证漏洞 CVE-2012-2122

漏洞影响版本 MariaDB versions from 5.1.62, 5.2.12, 5.3.6, 5.5.23 are not.MySQL versions from 5.1.63, 5.5.24, 5.6.6 are not.演示 开启靶场 进入漏洞目录 cd /root/vulhub/mysql/CVE-2012-2122开启漏洞靶场 docker-compose up -d攻击 直接 运行 这个命令 for i i…

【动态规划】简单多状态dp问题

1.按摩师 按摩师 思路&#xff1a; class Solution { public:int massage(vector<int>& nums) {//创建dp表//初始化//填表//返回值int n nums.size();if(n 0) return 0;vector<int> f(n);auto g f;f[0] nums[0];for(int i 1; i < n; i){f[i] g[i - 1…

地图涟漪效果

参考API echarts图表集 useEcharts.js import { onBeforeUnmount, onDeactivated } from "vue"; // import * as echarts from "echarts";/*** description 使用 Echarts (只是为了添加图表响应式)* param {Element} myChart Echarts实例 (必传)* param …

【C语言 | 字符串处理】sscanf 详细介绍、使用说明以及使用例子源码

&#x1f601;博客主页&#x1f601;&#xff1a;&#x1f680;https://blog.csdn.net/wkd_007&#x1f680; &#x1f911;博客内容&#x1f911;&#xff1a;&#x1f36d;嵌入式开发、Linux、C语言、C、数据结构、音视频&#x1f36d; ⏰发布时间⏰&#xff1a;2024-05-08 1…

虚拟机CentOS密码重置

1&#xff0c;reboot重启 在出现下面的界面1按e 如果有选项就选择“CentOS Linux &#xff08;3.10.0-327.e17.x86_64&#xff09;7 &#xff08;Core&#xff09;”【我的电脑没有直接显示界面2】 界面1 界面2 2&#xff0c;在上述界面2中继续按e进入编辑模式 找到“ro cr…

Ubuntu20.4部署Cuda12.4

准备Ubuntu20.4 VM 安装Cuda12.4 1.进入如下界面安装安装Cuda12.4版本&#xff1a; CUDA Toolkit 12.4 Update 1 Downloads | NVIDIA Developerhttps://developer.nvidia.com/cuda-downloads?target_osLinux&target_archx86_64&DistributionUbuntu&target_vers…

【谷粒商城】03创建商品模块

1.创建模块 2.创建项目微服务 商品服务、仓储服务、订单服务、优惠券服务、用户服务 共同&#xff1a; 1&#xff09;、web、openfeign 2&#xff09;、每一个服务&#xff0c;包名 com.atguigu.gulimall.xxx(product/order/ware/coupon/member) 3&#xff09;、模块名&#x…