当前位置:网站首页>WebSocket的实际应用
WebSocket的实际应用
2022-08-03 04:22:00 【破 风】
第一步 : 引入POM依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>第二步 :java代码如下
package com.ruoyi.web.controller.websoket;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
@ServerEndpoint(value = "/webSocket/dealWith")
@Component
public class WebSocketServer {
public static String userId = null;
@PostConstruct
public void init() {
System.out.println("websocket 加载");
}
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
public static Map<String,Session> map = new HashMap<>();
/**
* 连接建立成功调用的方法并打印出相关的数据
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
map.put(userId,session);
int cnt = OnlineCount.incrementAndGet(); // 在线数加1
System.out.printf("有连接加入,当前连接数为:"+ cnt);
SendMessage(session, "连接成功");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
System.out.printf("有连接关闭,当前连接数为:"+ cnt);
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.printf("来自客户端的消息:"+ message);
SendMessage(session, "收到消息,消息内容:"+ message);
}
/**
* 出现错误
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.printf("发生错误:{},Session ID: {}",error.getMessage(),session.getId());
error.printStackTrace();
}
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
System.out.printf("发送消息出错:"+ e.getMessage());
e.printStackTrace();
}
}
/**
* 群发消息
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if(session.isOpen()){
SendMessage(session, message);
}
}
}
/**
* 指定Session发送消息
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String message,String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if(s.getId().equals(sessionId)){
session = s;
break;
}
}
if(session!=null){
SendMessage(session, message);
}
else{
System.out.printf("没有找到你指定ID的会话:"+ sessionId);
}
}
}第三步 : 上JS代码
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket测试,客户端接收到的消息如下:</h3>
<textarea id = "messageId" readonly="readonly" cols="150" rows="30" >
</textarea>
<script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket");
//实现化WebSocket对象
//指定要连接的服务器地址与端口建立连接
//注意ws、wss使用不同的端口。我使用自签名的证书测试,
//无法使用wss,浏览器打开WebSocket时报错
//ws对应http、wss对应https。
socket = new WebSocket("ws://localhost:8085/project/dealWith");
//连接打开事件
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("消息发送测试(12356)");
};
//收到消息事件
socket.onmessage = function(msg) {
$("#messageId").append(msg.data+ "\n");
console.log(msg.data );
};
//连接关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
}
//窗口关闭时,关闭连接
window.unload=function() {
socket.close();
};
}
</script>
</body>
</html>后续补充:如果使用上面的代码socket报404的话可参考下面方法解决
报404我们首先要排除是我们项目自带拦截等限制问题,如果都没问题的话springBoot自身也会有一个使socket404问题,如何解决可参考下面代码,首先我们引入socker指定依赖,不能使用Spring自带的依赖,需要我们单独引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>引入socket的配置
package com.odcchina.fai.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}通过上面的步骤即可解决问题!!!!!!!!!!!!
边栏推荐
- 计组错题集
- DC-4靶场搭建及渗透实战详细过程(DC靶场系列)
- Record some bugs encountered - when mapstruct and lombok are used at the same time, the problem of data loss when converting entity classes
- 肖sir__自动化面试题
- 2022河南萌新联赛第(四)场:郑州轻工业大学 E - 睡大觉
- MySQL 删除表数据,重置自增 id 为 0 的两个方式
- conda常用命令合集
- 常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
- 普乐蛙VR台风体验馆厂家VR防震减灾模拟VR沉浸式体验设备
- 刚上线就狂吸70W粉,新型商业模式“分享购”来了,你知道吗?
猜你喜欢
随机推荐
【翻译】开发与生产中的Kubernetes修复成本对比
在竞争白热化的电商行业,链动2+1为什么还有企业在用
接口和协议
传统企业如何转型社交电商,泰山众筹的玩法有哪些?
v-text指令:设置标签内容
Record some bugs encountered - when mapstruct and lombok are used at the same time, the problem of data loss when converting entity classes
How many moments have you experienced the collapse of electronic engineers?
SM30 表维护视图数据保存前 数据校验事件
MySQL 删除表数据,重置自增 id 为 0 的两个方式
mysql bool盲注
工程制图-齿轮
【STM32】入门(四):外部中断-按键通过中断动作
Redis缓存雪崩、缓存穿透、缓存击穿
阿里面试官:聊聊如何格式化Instant
DC-4靶场搭建及渗透实战详细过程(DC靶场系列)
Shell编程的条件语句
WinForm的控件二次开发
ScanNet数据集讲解与点云数据下载
(2022杭电多校五)1010-Bragging Dice (思维)
GD32学习笔记(3)NAND Flash管理









