aries集成websocket实现实时通信
需要按照具体情况进行操作对于某些时候可能有相对改动
WebSocket 是一种通信协议,可在单个TCP 连接上进行全双工通信。WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就可以建立持久性的连接,并进行双向数据传输。
1、aries-framework/pom.xml 文件添加websocket 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、配置匿名访问
- shiro安全框架
filterChainDefinitionMap.put("/websocket/**", "anon");
- springScecurity
@Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers("/websocket/**");
}
3、将以下代码创建到对应位置,每一个代码块的第一行是对应的位置,这里仅仅只写出ruiyi分离版的,首先在framwork模块framwork包中创建websocker包然后分别创建对应的class文件,并且将下方代码复制进去
SemaphoreUtils : 信号量相关处理
package com.ruoyi.framework.websocket;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SemaphoreUtils
{
private static final Logger LOGGER = LoggerFactory.getLogger(SemaphoreUtils.class);
public static boolean tryAcquire(Semaphore semaphore)
{
boolean flag = false;
try
{
flag = semaphore.tryAcquire();
}
catch (Exception e)
{
LOGGER.error("获取信号量异常", e);
}
return flag;
}
public static void release(Semaphore semaphore)
{
try
{
semaphore.release();
}
catch (Exception e)
{
LOGGER.error("释放信号量异常", e);
}
}
}
WebSocketConfig : websocket 配置
package com.ruoyi.framework.websocket;
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();
}
}
WebSocketServer : websocket 消息处理
package com.ruoyi.framework.websocket;
import java.util.concurrent.Semaphore;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer
{
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
public static int socketMaxOnlineCount = 100;
private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);
@OnOpen
public void onOpen(Session session) throws Exception
{
boolean semaphoreFlag = false;
semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
if (!semaphoreFlag)
{
LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数:" + socketMaxOnlineCount);
session.close();
}
else
{
WebSocketUsers.put(session.getId(), session);
LOGGER.info("\n 建立连接 - {}", session);
LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
WebSocketUsers.sendMessageToUserByText(session, "连接成功");
}
}
@OnClose
public void onClose(Session session)
{
LOGGER.info("\n 关闭连接 - {}", session);
WebSocketUsers.remove(session.getId());
SemaphoreUtils.release(socketSemaphore);
}
@OnError
public void onError(Session session, Throwable exception) throws Exception
{
if (session.isOpen())
{
session.close();
}
String sessionId = session.getId();
LOGGER.info("\n 连接异常 - {}", sessionId);
LOGGER.info("\n 异常信息 - {}", exception);
WebSocketUsers.remove(sessionId);
SemaphoreUtils.release(socketSemaphore);
}
@OnMessage
public void onMessage(String message, Session session)
{
String msg = message.replace("你", "我").replace("吗", "");
WebSocketUsers.sendMessageToUserByText(session, msg);
}
}
WebSocketUsers : websocket 客户端用户集
package com.ruoyi.framework.websocket;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebSocketUsers
{
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUsers.class);
private static Map<String, Session> USERS = new ConcurrentHashMap<String, Session>();
public static void put(String key, Session session)
{
USERS.put(key, session);
}
public static boolean remove(Session session)
{
String key = null;
boolean flag = USERS.containsValue(session);
if (flag)
{
Set<Map.Entry<String, Session>> entries = USERS.entrySet();
for (Map.Entry<String, Session> entry : entries)
{
Session value = entry.getValue();
if (value.equals(session))
{
key = entry.getKey();
break;
}
}
}
else
{
return true;
}
return remove(key);
}
public static boolean remove(String key)
{
LOGGER.info("\n 正在移出用户 - {}", key);
Session remove = USERS.remove(key);
if (remove != null)
{
boolean containsValue = USERS.containsValue(remove);
LOGGER.info("\n 移出结果 - {}", containsValue ? "失败" : "成功");
return containsValue;
}
else
{
return true;
}
}
public static Map<String, Session> getUsers()
{
return USERS;
}
public static void sendMessageToUsersByText(String message)
{
Collection<Session> values = USERS.values();
for (Session value : values)
{
sendMessageToUserByText(value, message);
}
}
public static void sendMessageToUserByText(Session session, String message)
{
if (session != null)
{
try
{
session.getBasicRemote().sendText(message);
}
catch (IOException e)
{
LOGGER.error("\n[发送消息异常]", e);
}
}
else
{
LOGGER.info("\n[你已离线]");
}
}
}
4、测试验证
如果要测试验证可以把websocket.html 内容复制到login.html ,点击连接发送消息测试返回结果。
websocket.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>测试界面</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
</head>
<body>
<div>
<input type="text" style="width: 20%" value="ws://127.0.0.1:80/websocket/message" id="url">
<button id="btn_join">连接</button>
<button id="btn_exit">断开</button>
</div>
<br/>
<textarea id="message" cols="100" rows="9"></textarea> <button id="btn_send">发送消息</button>
<br/>
<br/>
<textarea id="text_content" readonly="readonly" cols="100" rows="9"></textarea>返回内容
<br/>
<br/>
<script type="text/javascript">
$(document).ready(function(){
var ws = null;
$('#btn_join').click(function() {
var url = $("#url").val();
ws = new WebSocket(url);
ws.onopen = function(event) {
$('#text_content').append('已经打开连接!' + '\n');
}
ws.onmessage = function(event) {
$('#text_content').append(event.data + '\n');
}
ws.onclose = function(event) {
$('#text_content').append('已经关闭连接!' + '\n');
}
});
$('#btn_send').click(function() {
var message = $('#message').val();
if (ws) {
ws.send(message);
} else {
alert("未连接到服务器");
}
});
$('#btn_exit').click(function() {
if (ws) {
ws.close();
ws = null;
}
});
})
</script>
</body>
</html>
|