websocket使用-1

WebSocket

package com.zzdy.applet.websocker;

import com.alibaba.fastjson.JSONObject;
import com.zzdy.applet.utils.ReturnData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/ocppTool/{sn}/{channels}") //此注解相当于设置访问URL
public class WebSocket {
private Session session;

private static final CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
/*
websocket是客户端和服务端之间建立了一个连接,建立完连接以后,会生成一个websocket对象,我们可以用这个对象来执行发送,接收等操作。但是这只是一个存在于客户端与服务器之间的链接,换句话说,
系统只能识别到这个websocket连接是对应于哪个页面(浏览器),
而这个页面在系统中是对应哪个用户(数据库中的用户,或者根本就没有对应任何用户,即未登录,只是一个游客),我
们是无法从这个websocket对象中获取的。所以我们需要创建一个Map对象,用于将websocket对象和实际的user对象进行关联,这样为我们后续向特定的用户推送消息做铺垫
*/
private static final Map<String, Session> sessionPool = new HashMap<>();
/**
* 处理类
*/
WebSocketService webSocketService;

public WebSocket() {
// 在构造函数中实例化服务类
webSocketService = new WebSocketService();
}
String snType="1";
@OnOpen
public void onOpen(Session session, @PathParam(value = "sn") String sn,@PathParam(value = "channels") String channels) {
try {
this.session = session;
webSockets.add(this);
sessionPool.put(snType+sn+channels, session);
log.info("【websocket消息】有新的连接,总数为: {}", webSockets.size());
// 发送消息
onMessageMeterValues(sn,channels);
} catch (Exception e) {
}
}

@OnClose
public void onClose(@PathParam(value = "sn") String sn,@PathParam(value = "channels") String channels) {
try {
webSockets.remove(this);
sessionPool.remove(snType+sn+channels);
log.info("【websocket消息】连接断开,总数为: {}", webSockets.size());
} catch (Exception e) {
}
}

/**
* 发送消息
* 主动发送
* @param sn
* @param channels
*/
public void onMessageMeterValues(String sn,String channels) {
Map<String,Object> data=new HashMap<>();
data.put("cmd","meterValues");
data.put("channel",channels);
ReturnData resultData=webSocketService.dataAnalysisService(snType+sn,data.toString());
session.getAsyncRemote().sendText(JSONObject.toJSONString(resultData));
}

@OnMessage
public void onMessage(@PathParam("sn") String sn,@PathParam("channels") String channels,String message) {
ReturnData resultData=webSocketService.dataAnalysisService(snType+sn,message);
session.getAsyncRemote().sendText(JSONObject.toJSONString(resultData));
}
@OnError
public void OnError(Session session, @PathParam(value = "sn") String sn,@PathParam(value = "channels") String channels, Throwable t) {
try {
if (session.isOpen()) {
session.close();
}
webSockets.remove(this);
sessionPool.remove(snType+sn);
log.info("【websocket消息】连接[错误]断开,总数为: {}, 错误:{}", webSockets.size(), t.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 此为广播消息
* @param message
*/
public void sendAllMessage(String message) {
log.info("【websocket消息】广播消息:" + message);
for (WebSocket webSocket : webSockets) {
try {
if (webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 此为单点消息
* @param sn
* @param message
*/
public void sendOneMessage(String sn, String message) {
Session session = sessionPool.get(snType+sn);
if (null!=session && session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
* 此为单点消息(多人)
*/
public void sendMoreMessage(String[] sns, String message) {
for (String sn : sns) {
Session session = sessionPool.get(snType+sn);
if (null!=session && session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:" + message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

/**
* 增加就缓存值
* @param value
*/
public void addToCache(String value) {

}

}

WebSocketConfig

package com.zzdy.applet.websocker;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
/**
* 会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
* 要注意,如果使用独立的servlet容器,
* 而不是直接使用springboot的内置容器,
* 就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

WebSocketService-业务逻辑处理

package com.zzdy.applet.websocker;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.zzdy.applet.utils.ReturnData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* websocker业务逻辑处理类
*/
@Service
public class WebSocketService {
/**
* 消息处理
* @param message 接收到消息 {"cmd":"meterValues","channel":1}
* @param sn 设备sn号
* @return
*/
public ReturnData dataAnalysisService(String sn,String message) {
ReturnData returnData=new ReturnData();
try{
if(StringUtils.isNotBlank(message)){
Map<String,Object> data=(Map)JSONObject.parse(message);
// 类型
String cmd=data.get("cmd")==null?"":String.valueOf(data.get("cmd"));
// 枪号
String channel=data.get("channel")==null?"":String.valueOf(data.get("channel"));
/**
* 获取数据
*/
if(CmdEnum.meterValues.getCode().equals(cmd)){
returnData.setData(getMeterValues(sn,channel));
returnData.setResult(true);
returnData.setMsg("获取数据成功");
returnData.setCode("000000");
}
}else{
returnData.setData(null);
returnData.setResult(false);
returnData.setMsg("接收到消息为空");
returnData.setCode("111111");
}
}catch (Exception e){
e.printStackTrace();
}
return returnData;
}
/**
* 获取数据
*/
private Map<String,Object> getMeterValues(String sn,String channel){
Map<String,Object> data=new HashMap<>();
try{
Cache cache = Redis.use();
JSONObject meterValuesObj=cache.get(sn+channel);


}catch (Exception e){
e.printStackTrace();
}
return data;
}
}

相关推荐

  1. websocket使用-1

    2024-01-05 12:34:06       28 阅读
  2. webSocket使用

    2024-01-05 12:34:06       33 阅读
  3. Go使用websocket

    2024-01-05 12:34:06       36 阅读
  4. uni-app使用WebSocket

    2024-01-05 12:34:06       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-05 12:34:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-05 12:34:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-05 12:34:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-05 12:34:06       18 阅读

热门阅读

  1. Qt3D 材质模块使用说明

    2024-01-05 12:34:06       31 阅读
  2. RabbitMQ

    RabbitMQ

    2024-01-05 12:34:06      33 阅读
  3. 设计模式之观察者模式

    2024-01-05 12:34:06       33 阅读
  4. 类和对象及其关系

    2024-01-05 12:34:06       32 阅读
  5. TP-GMM

    TP-GMM

    2024-01-05 12:34:06      28 阅读