三步学会使用WebSocekt

devtools/2024/10/21 10:08:02/

目录

websocket-toc" style="margin-left:0px;">一 什么是websocket

websocket-toc" style="margin-left:0px;">二 如何使用websocket

websocket%E7%9A%84maven%E5%9D%90%E6%A0%87-toc" style="margin-left:40px;">1.导入websocket的maven坐标

websocket%E7%9A%84%E6%9C%8D%E5%8A%A1%E7%B1%BB%C2%A0-toc" style="margin-left:40px;">2.创建websocket的服务类 

websocket%E7%9A%84%E9%85%8D%E7%BD%AE%E7%B1%BB-toc" style="margin-left:40px;">3.创建websocket的配置类

4.按需求实现业务逻辑

websocket-toc" style="margin-left:40px;">5.前端实现websocket


websocket">一 什么是websocket

        websocket和HTTP一样是基于TCP的一个通信协议。不过他是支持客户端和服务端双向通信的协议 。

        和HTTP不同的是,websocket是长连接 , HTTP是短连接 ,因为websocket只要客户端可服务端建立好了连接,除了主动关闭连接 , 他们发送完信息不会自动断开 , 而HTTP客户端向服务端发送一次连接,服务端返回后,就会断开连接 , 下次再发就要重新建立连接。

        而且HTTP只能是客户端主动向服务端发送信息 , 服务端接收,然后再返回。而websockt的服务端和客户端的通信是双向的,客户端可以主动向服务端发送信息 , 服务端也可以主动向客户端发送信息。

websocket">二 如何使用websocket

websocket%E7%9A%84maven%E5%9D%90%E6%A0%87">1.导入websocket的maven坐标

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

websocket%E7%9A%84%E6%9C%8D%E5%8A%A1%E7%B1%BB%C2%A0">2.创建websocket的服务类 

package com.sky.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.util.Collection;
import java.util.HashMap;
import java.util.Map;/*** WebSocket服务*/
@Component
@ServerEndpoint("/ws/{sid}")  //连接路径
public class WebSocketServer {//存放会话对象private static Map<String, Session> sessionMap = new HashMap();/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {System.out.println("客户端:" + sid + "建立连接");sessionMap.put(sid, session);}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);}/*** 连接关闭调用的方法** @param sid*/@OnClosepublic void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);}/*** 群发** @param message*/public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}

① 你可以把这个类看成一个websocket的Controller类,因为前端页面(客户端)会设置一个连接服务端websocket的路径,就是

@ServerEndpoint("/ws/{sid}")  //连接路径

这个路径,需要和前端保持一致。

② 然后连接成功之后 , 就会创建一个连接对象 , 把客户端连接对象存储到

private static Map<String, Session> sessionMap = new HashMap();

③ 这个map集合中,String就是上面的{sid}这个参数是前端传来的,作为对象的标识。

剩下的

onOpen()

方法上面加了注解 , 只要客户端与服务端连接成功 , 就会自动调用这个方法。

④ 还有下面这个方法

/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);
}

这个方法是收到客户端发送的信息(页面) ,就会自动调用这个方法 , 同时把客户端的标识已经客户端发送的信息当作参数传来。

⑤ 还有这个关闭连接的方法

/*** 连接关闭调用的方法** @param sid*/
@OnClose
public void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);
}

这个方法是在我们关闭连接的时候自动执行。

⑥ 最后一个方法

public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}
}

这个方法上面没有任何注解 , 也就是说不能自动执行 , 需要我们调用才会执行 , 他的主要作用就是服务端向客户端发送信息 , 而且我们可以按照需求 , 在不同的逻辑下按需要调用这个方法,来向客户端发送信息 。而且这里是群发 ,因为我是直接遍历map集合中的所有客户端对象进行发送。

websocket%E7%9A%84%E9%85%8D%E7%BD%AE%E7%B1%BB">3.创建websocket的配置类

package com.sky.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** WebSocket配置类,用于注册WebSocket的Bean*/
@Configuration
public class WebSocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

这个配置类主要用于创建websocket的Bean来做一些初始化

4.按需求实现业务逻辑

        在这里websocket基本配置已经完成了,最后只需要按照自己业务需求去与客户端进行通信就可以了 ,我在这里做一个示例:

        比如我需要每3秒向客户端发送当前时间的信息,而客户端可以主动向服务端发送信息。

        所以这里我就需要使用定时任务springTask来实现这个业务逻辑,每3秒调用向客户端发送信息的方法。实现代码如下:

package com.sky.task;import com.sky.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;@Component
public class WebSocketTask {@Autowiredprivate WebSocketServer webSocketServer;/*** 通过WebSocket每隔5秒向客户端发送消息*/@Scheduled(cron = "0/5 * * * * ?")public void sendMessageToClient() {webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));}
}

 

websocket">5.前端实现websocket

        前端也需要实现websocket相关代码,但是代码都是一样的 , 所以我这里直接将我的前端代码给大家展示出来:

<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"><title>WebSocket Demo</title>
</head>
<body><input id="text" type="text" /><button onclick="send()">发送消息</button><button onclick="closeWebSocket()">关闭连接</button><div id="message"></div>
</body>
<script type="text/javascript">var websocket = null;var clientId = Math.random().toString(36).substr(2);//判断当前浏览器是否支持WebSocketif('WebSocket' in window){//连接WebSocket节点websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(){setMessageInnerHTML("连接成功");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}//关闭连接function closeWebSocket() {websocket.close();}
</script>
</html>

 最终演示结果如下:

以上就是websocket的基本使用 , 主要代码都是一样的,使用时直接cv即可,只需要实现自己的需求逻辑这部分代码。


http://www.ppmy.cn/devtools/57408.html

相关文章

SpringBoot实战:轻松实现XSS攻击防御(注解和过滤器)

文章目录 引言一、XSS攻击概述1.1 XSS攻击的定义1.2 XSS攻击的类型1.3 XSS攻击的攻击原理及示例 二、Spring Boot中的XSS防御手段2.1 使用注解进行XSS防御2.1.1 引入相关依赖2.1.2 使用XSS注解进行参数校验2.1.3 实现自定义注解处理器2.1.4 使用注解 2.2 使用过滤器进行XSS防御…

【微信小程序开发实战项目】——如何制作一个属于自己的花店微信小程序(1)

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;开发者-曼亿点 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 曼亿点 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a…

[pwn]静态编译

静态编译 1. 栈足够大的情况下 程序在ida打开后&#xff0c;左侧的函数栏目没有红色&#xff08;系统调用的函数&#xff09;&#xff0c;而只有一些静态函数&#xff0c;通常这类文件的大小会必普通的pwn题程序要大得多。 这种静态编译的题没有调用库函数&#xff0c;也就没…

adb热更新

模拟器连接AndroidStudio 解决:adb server version (36) doesnt match this client (40); killing... 1.G:\ProgramFils\android-sdk\platform-tools adb --version 2.H:\yeshen\Nox\bin adb --version 3.把G:\ProgramFils\android-sdk\platform-…

怎么配置electron-updater

electron-updater 是一个流行的 Electron 应用程序更新解决方案,它允许你的 Electron 应用自动检查、下载并安装新版本。以下是如何配置 electron-updater 的基本步骤: 1. 安装依赖 首先,你需要在你的 Electron 项目中安装 electron-updater 和相关的打包工具(如 electro…

在Linux环境下使用sqlite3时,如果尝试对一个空表进行操作(例如插入数据),可能会遇到表被锁定的问题。

在Linux环境下使用sqlite3时&#xff0c;如果尝试对一个空表进行操作&#xff08;例如插入数据&#xff09;&#xff0c;可能会遇到表被锁定的问题。这通常是因为sqlite3在默认情况下会对空表进行“延迟创建”&#xff0c;即在实际需要写入数据之前&#xff0c;表不会被真正创建…

计算机大方向的选择

选专业要了解自己的兴趣所在。 即想要学习什么样的专业&#xff0c;如果有明确的专业意向&#xff0c;就可以有针对性地选择那些专业实力较强的院校。 2.如果没有明确的专业意向&#xff0c;可以优先考虑一下院校。 确定一下自己想要选择综合性院校还是理工类院校或是像财经或者…

【计算机毕业设计】073智慧旅游平台开发微信小程序

&#x1f64a;作者简介&#xff1a;拥有多年开发工作经验&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的项目或者毕业设计。 代码可以私聊博主获取。&#x1f339;赠送计算机毕业设计600个选题excel文件&#xff0c;帮助大学选题。赠送开题报告模板&#xff…