springboot 集成webSocket
2023-04-18 16:30:12 时间
1、什么是webSocket?
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
1.新建config包,创建WebSocketConfig类
@Configuration public class WSConfiguration { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
2.新建service包,创建WebSocketServer类
@Component @ServerEndpoint("/websocket") public class WebSocketServer { //准备一个内部安全的集合 存放所有用户的websocket服务 private static CopyOnWriteArraySet<WebSocketServer> wsset = new CopyOnWriteArraySet<>(); private Session session; @OnOpen public void opOpen(Session session){ this.session=session; //将自身填充到set集合中 这个集合是所有客户端websocket的集合 wsset.add(this); sendMsg(); } @OnClose public void onClose(){ //将自己从set集合中删除 wsset.remove(this); } @OnError public void onError(Session session,Throwable error){ System.out.println(this+"发生错误了"); } //客户端发来消息 @OnMessage public void onMessage(String clientMsg, Session session){ System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg); //每隔一秒给你推送一条当前时间信息 } private void sendMsg(){ try { while(true){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time =sdf.format(new Date()); //发送数据 this.session.getBasicRemote().sendText(time); Thread.sleep(1000); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
3.controller层加注解
@SpringBootApplication @EnableWebSocket public class MywebsocketApplication { public static void main(String[] args) { SpringApplication.run(MywebsocketApplication.class, args); } }
4在resources下编写HTMl
<html> <head> </head> <body> <div id="time"></div> <script type="text/javascript"> //new WebSocket var webSocket = new WebSocket("ws://localhost:8080/websocket"); webSocket.onopen = function () { } webSocket.onopen=function () { } webSocket.onclose=function () { } webSocket.οnerrοr=function () { } webSocket.onmessage=function (msg) { document.getElementById("time").innerHTML=msg.data; } </script> </body> </html>
5网页访问
http://localhost:8080/
6 WebSocketServer同步发送消息
package com.kgc.mywebsocket.commons; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; @Component @ServerEndpoint("/websocket") public class WebSocketServer { //准备一个内部安全的集合 存放所有用户的websocket服务 private static CopyOnWriteArraySet<WebSocketServer> wsset = new CopyOnWriteArraySet<>(); private Session session; @OnOpen public void opOpen(Session session){ this.session=session; //将自身填充到set集合中 这个集合是所有客户端websocket的集合 wsset.add(this); // sendMsg(); } @OnClose public void onClose(){ //将自己从set集合中删除 wsset.remove(this); } @OnError public void onError(Session session,Throwable error){ System.out.println(this+"发生错误了"); } //客户端发来消息 @OnMessage public void onMessage(String clientMsg, Session session){ System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg); //每隔一秒给你推送一条当前时间信息 sendAllClient(clientMsg); } private void sendMsg(){ try { while(true){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time =sdf.format(new Date()); //发送数据 this.session.getBasicRemote().sendText(time); Thread.sleep(1000); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void sendAllClient(String msg){ try { for(WebSocketServer wss:wsset){ wss.session.getBasicRemote().sendText(msg); } } catch (IOException e) { e.printStackTrace(); } } }
7 html同步发送消息
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <html> <head> </head> <body> <div id="time"></div> ========== <input type="text" id="txtMsg"/> ========== <br/> <button type="button" οnclick="sendMsg()">发送消息</button> <br/> <script type="text/javascript"> //new WebSocket var webSocket = new WebSocket("ws://localhost:8080/websocket"); function sendMsg(){ var txt =document.getElementById("txtMsg").value; webSocket.send(txt); } webSocket.onopen = function () { } webSocket.onclose=function () { } webSocket.οnerrοr=function () { } webSocket.onmessage=function (msg) { document.getElementById("time").innerHTML=msg.data; } </script> </body> </html>
http://localhost:8080/
相关文章
- 【技术种草】cdn+轻量服务器+hugo=让博客“云原生”一下
- CLB运维&运营最佳实践 ---访问日志大洞察
- vnc方式登陆服务器
- 轻松学排序算法:眼睛直观感受几种常用排序算法
- 十二个经典的大数据项目
- 为什么使用 CDN 内容分发网络?
- 大数据——大数据默认端口号列表
- Weld 1.1.5.Final,JSR-299 的框架
- JavaFX 2012:彻底开源
- 提升as3程序性能的十大要点
- 通过凸面几何学进行独立于边际的在线多类学习
- 利用行动影响的规律性和部分已知的模型进行离线强化学习
- ModelLight:基于模型的交通信号控制的元强化学习
- 浅谈Visual Source Safe项目分支
- 基于先验知识的递归卡尔曼滤波的代理人联合状态和输入估计
- 结合网络结构和非线性恢复来提高声誉评估的性能
- 最佳实践丨云开发CloudBase多环境管理实践
- TimeVAE:用于生成多变量时间序列的变异自动编码器
- 具有线性阈值激活的神经网络:结构和算法
- 内网渗透之横向移动 -- 从域外向域内进行密码喷洒攻击