当前位置:网站首页>Practical application of WebSocket
Practical application of WebSocket
2022-08-03 04:33:00 【breaking wind】
第一步 : 引入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<>();
/**
* The connection is established to successfully call the method and print out the relevant data
*/
@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报404If so, you can refer to the following methods to solve it
报404We must first rule out the limitation of our project's built-in interception,如果都没问题的话springBootIt will also have an ambassadorsocket404问题,How to solve can refer to the code below,首先我们引入socker指定依赖,不能使用Spring自带的依赖,need us to quote separately
<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();
}
}
The problem can be solved by the above steps!!!!!!!!!!!!
边栏推荐
猜你喜欢
随机推荐
数值类型转换02
好消息!北京、珠海PMP考试时间来啦
Kotlin-Flow common encapsulation class: the use of StateFlow
mysql bool blind
5.回顾简单的神经网络
CyberArk被评为2022年Gartner特权访问管理魔力象限领导者
path development介绍
OpenFOAM提取等职面并计算面积
DC-6靶场下载及渗透实战详细过程(DC靶场系列)
超好用的画图工具推荐
肖sir__简历
私域流量引流方法?分享购火爆的商业模式,你值得拥有
接口测试实战| GET/POST 请求区别详解
I ported GuiLite to STM32F4 board
JS底层手写
EssilorLuxottica借助Boomi的智能集成平台实现订单处理的现代化
接口测试框架实战(四)| 搞定 Schema 断言
mysql 创建索引的三种方式
Record some bugs encountered - when mapstruct and lombok are used at the same time, the problem of data loss when converting entity classes
Jmeter 模拟多用户登录的两种方法