WebSocket 使用记录
2024-10-21 11:58:00
WebSocket 主要解决的问题是 后端数据更新主动像前端推送数据
所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
开启Websocket 支持
package com.example.dome; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; import javax.websocket.server.ServerEndpoint; /**
* @author SPC-044
* @date 13:39
* @Version 1.0
*/ @Configuration
public class WebSocketConfig { @Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
WebSocket 拦截服务类
package com.example.dome; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap; /**
* @author SPC-044
* @date 10:57
* @Version 1.0
*/
@ServerEndpoint("/webSocket/{id}")
@RestController
public class WebSocket { private static final Logger loger = LoggerFactory.getLogger(WebSocket.class); private static volatile int onlineCount = 0; // private static CopyOnWriteArraySet<WebSocket> webSocketSet =new CopyOnWriteArraySet(); private String id;
private static ConcurrentHashMap<String,WebSocket> webSocketMap = new ConcurrentHashMap(); private Session session;
@OnOpen
public void onOpen(Session session, @PathParam("id") String id){ //新建连接时调用
this.session=session;
this.id =id;
webSocketMap.put(id,this);
// webSocketSet.add(this);
loger.info("openWebSocket id={},name={}",id);
} @OnClose
public void onClose(){ //关闭链接时调用
if(webSocketMap.containsKey(id)){
webSocketMap.remove(id);
}
// webSocketSet.remove(this); loger.info("closeWebSocket。。。");
} @OnMessage
public void onMessage(String messsge,Session session){ //接受前端消息
loger.info("收到消息{}",messsge);
try { // sendMessage(messsge);
} catch (Exception e) {
e.printStackTrace();
}
} @OnError
public void onError(Session session,Throwable error){ //链接异常时访问
loger.info("链接错误");
} private void sendMessage(String message) throws Exception {
if(this.session.isOpen()){
this.session.getBasicRemote().sendText(message);
}
} public static void sendInfo(String id,String message){ // 后端主动像前端推消息
if(webSocketMap.get(id) !=null && webSocketMap.containsKey(id)){
try {
webSocketMap.get(id).sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}else {
loger.info("该用户不在线!");
}
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>123</p>
<button name="test" value="模拟建立链接" onclick="lianjie()" >test</button>
</body> <script type="text/javascript">
// 加载页面时生成随机数模拟不同用户的 Id
var id = Math.ceil(Math.random()*10);
console.log(id);
function lianjie() {
send();
}
// 加载页面时 建立链接 id 用于区分不同用户
var webSocket = new WebSocket("ws://127.0.0.1:8082/webSocket/"+id); webSocket.onerror = function () {
console.log("链接错误");
} webSocket.onopen = function () {
console.log("链接成功");
} webSocket.onmessage =function (event) {
console.log(event.data);
} webSocket.onclose = function () {
console.log("关闭链接");
} function closeWebSocket() {
webSocket.close();
} function send() {
webSocket.send("第一次发消息");
} </script>
</html>
后端主动像前端推送消息
WebSocket.sendInfo("10", "id 10 你好"); 传入 用户id 及消息
@RequestMapping("/webSocketTest")
public void websocketTest(){ Thread thread = new Thread(() -> {
WebSocket.sendInfo("1", "id 1 你好");
}); Thread thread1 = new Thread(() -> {
WebSocket.sendInfo("10", "id 10 你好");
}); thread.start();
thread1.start(); }
最新文章
- nth-of-type在选择class的时候需要注意的一个小问题
- Google开源SLAM软件cartographer中使用的UKF滤波器解析
- 利用linux漏洞进行提权
- virtualbox创建com对象失败(解决方法)
- 【iCore3 双核心板】例程十七:USB_MSC实验——读/写U盘(大容量存储器)
- android开发 BaseAdapter中getView()里的3个参数是什么意思
- 五、案例-指令参考-freemarker指令、表达式
- android:descendantFocusability的作用:viewgroup与其上面view的焦点控制,如何让子view失去焦点等。
- 中文版kendoUI API — Grid(一)
- Mysql相关操作
- Bootstrap 静态分页 和 jquery_pagination插件 动态分页
- CentOS下利用sshpass不用手动输入密码远程执行命令
- 【算法系列学习】codeforces C. Mike and gcd problem
- 把ajax包装成promise的形式(1)
- Spring学习记录
- CentOS安装和配置Mysql
- Fiddler怎样抓取手机的包
- onems设备管理系统(TR-069和OMA)
- open &#39;/dev/hwlog_switch&#39; fail -1, 13. Permission denied
- install the Mondo Rescue utility in Ubuntu 12.04 or 12.10.
热门文章
- Hystrix容错监控机制
- 对Jim博士质疑的质疑
- Python:Excel自动化实践入门篇 甲【留言点赞领图书门票】
- Vulhub 漏洞学习之:Apereo CAS
- Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0.
- chai 3D 之网格对象
- LeetCode-2013 检测正方形
- Oracle 11g 单机服务器ASM部署
- spring 特性
- 【研究生学习】SNR、Eb/N0和Es/N0的关系