新版onlyoffice
This commit is contained in:
@@ -8,7 +8,7 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
/**
|
||||
* @BelongsProject: leaf-onlyoffice
|
||||
* @BelongsPackage: com.ideayp.leaf.config
|
||||
* @Author: TongHui
|
||||
*
|
||||
* @CreateTime: 2022-12-01 17:37
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* MybatisPlusConfig.java
|
||||
* @Author TongHui MybatisPlusConfig.java
|
||||
* @Description 配置分页插件
|
||||
* @Date 2022/3/24 9:51
|
||||
* @Version 1.0
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.oo.demo.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();
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,12 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.oo.demo.entity.OnFile;
|
||||
import com.oo.demo.entity.Result;
|
||||
import com.oo.demo.entity.SysUser;
|
||||
import com.oo.demo.entity.WebsocketResult;
|
||||
import com.oo.demo.service.FileService;
|
||||
import com.oo.demo.service.OnFileService;
|
||||
import com.oo.demo.service.TempUser;
|
||||
import com.oo.demo.service.Oprator;
|
||||
import com.oo.demo.service.WebSocketServer;
|
||||
import com.oo.onlyoffice.api.OnlyServiceAPI;
|
||||
import com.oo.onlyoffice.dto.edit.FileUser;
|
||||
import com.oo.onlyoffice.tools.FileUtil;
|
||||
@@ -16,6 +19,7 @@ import com.oo.onlyoffice.tools.SecurityUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -31,7 +35,6 @@ import java.util.*;
|
||||
/**
|
||||
* @BelongsProject: leaf-onlyoffice
|
||||
* @BelongsPackage: com.ideayp.leaf.onlyoffice.controller
|
||||
* @Author: TongHui
|
||||
* @CreateTime: 2022-11-08 18:11
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
@@ -78,7 +81,7 @@ public class OnlyOfficeController {
|
||||
|
||||
@PostMapping("/files/upload")
|
||||
@ResponseBody
|
||||
public Object upload(@RequestParam("file") MultipartFile[] file) {
|
||||
public Object upload(@RequestParam("file") MultipartFile[] file, @RequestParam(name = "caseId") String caseId) {
|
||||
List<OnFile> result = new ArrayList<>();
|
||||
int i = 0;
|
||||
for (MultipartFile multipartFile : file) {
|
||||
@@ -101,6 +104,7 @@ public class OnlyOfficeController {
|
||||
onFile.setFileSize(commonsMultipartFile.getSize());
|
||||
onFile.setFileType(suffix);
|
||||
onFile.setFilePath(filepath + "/" + fileId + "." + suffix);
|
||||
onFile.setCaseId(caseId);
|
||||
onFileService.save(onFile);
|
||||
result.add(onFile);
|
||||
i++;
|
||||
@@ -112,13 +116,16 @@ public class OnlyOfficeController {
|
||||
return Result.error("文件上传失败");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
StringRedisTemplate stringRedisTemplate;
|
||||
final static String REDISUSERPREFIX = "user_key:";
|
||||
|
||||
/**
|
||||
* 打开编辑
|
||||
*/
|
||||
@RequestMapping("/onlyOfficeConfig/{mode}/{id}")
|
||||
@RequestMapping("/onlyOfficeConfig/{mode}/{id}/{userId}")
|
||||
@ResponseBody
|
||||
public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, Model model) {//@RequestParam("url") String url,
|
||||
public Object openDocument(@PathVariable(required = false) String mode, @PathVariable(required = false) String id, @PathVariable(required = true) Integer userId, Model model) {//@RequestParam("url") String url,
|
||||
log.info("only office file:" + id);
|
||||
OnFile onFile = onFileService.getById(id);
|
||||
if (onFile == null) {
|
||||
@@ -128,9 +135,20 @@ public class OnlyOfficeController {
|
||||
* 必要步骤
|
||||
*/
|
||||
FileUser user = new FileUser();
|
||||
user.setId(TempUser.getUserId());
|
||||
user.setName(TempUser.getUserName());
|
||||
SecurityUtils.setUserSession(user);
|
||||
//获取缓存Redis中的用户信息
|
||||
String userString = stringRedisTemplate.opsForValue().get(REDISUSERPREFIX + userId);
|
||||
if (userString != null && !"".equals(userString)) {
|
||||
JSONObject userObj = JSON.parseObject(userString);
|
||||
String userId1 = userObj.getString("userId");
|
||||
String userName1 = userObj.getString("userName");
|
||||
String nickName1 = userObj.getString("nickName");
|
||||
user.setId(userId1);
|
||||
user.setName(userName1);
|
||||
user.setNickname(nickName1);
|
||||
SecurityUtils.setUserSession(user);
|
||||
} else {
|
||||
return Result.error("当前用户不存在");
|
||||
}
|
||||
/**
|
||||
* 必要步骤
|
||||
*/
|
||||
@@ -197,7 +215,7 @@ public class OnlyOfficeController {
|
||||
*/
|
||||
@RequestMapping("/onlyOffice/save")
|
||||
@ResponseBody
|
||||
public Object saveFile(HttpServletRequest request, HttpServletResponse response) {
|
||||
public void saveFile(HttpServletRequest request, HttpServletResponse response) {
|
||||
PrintWriter writer = null;
|
||||
try {
|
||||
writer = response.getWriter();
|
||||
@@ -206,24 +224,19 @@ public class OnlyOfficeController {
|
||||
String body = scanner.hasNext() ? scanner.next() : "";
|
||||
JSONObject jsonObject = JSONObject.parseObject(body);
|
||||
log.info("{}", jsonObject);
|
||||
|
||||
Object result = fileService.documentSave(jsonObject);
|
||||
WebsocketResult result = fileService.documentSave(jsonObject);
|
||||
/*
|
||||
* status = 1,我们给onlyOffice的服务返回{"error":"0"}的信息。
|
||||
* 这样onlyOffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
|
||||
*/
|
||||
if (Objects.nonNull(writer)) {
|
||||
writer.write("{\"error\":0}");
|
||||
}
|
||||
return result;
|
||||
WebSocketServer.sendInfo(JSON.toJSONString(result.getOnFile()),result.getUserId());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
writer.write("{\"error\":-1}");
|
||||
return Result.error("保存出错");
|
||||
}
|
||||
/*
|
||||
* status = 1,我们给onlyOffice的服务返回{"error":"0"}的信息。
|
||||
* 这样onlyOffice会认为回调接口是没问题的,这样就可以在线编辑文档了,否则的话会弹出窗口说明
|
||||
*/
|
||||
// if (Objects.nonNull(writer)) {
|
||||
// writer.write("{\"error\":0}");
|
||||
// }
|
||||
}
|
||||
|
||||
@PostMapping("/save/{id}")
|
||||
@@ -238,11 +251,11 @@ public class OnlyOfficeController {
|
||||
*/
|
||||
try {
|
||||
FileUser user = new FileUser();
|
||||
user.setId(TempUser.getUserId());
|
||||
user.setName(TempUser.getUserName());
|
||||
user.setId(Oprator.getUserId());
|
||||
user.setName(Oprator.getUserName());
|
||||
SecurityUtils.setUserSession(user);
|
||||
String key = onlyServiceAPI.getKey(onFile.getFileId());
|
||||
String msg = onlyServiceAPI.save(key, TempUser.getUserId());
|
||||
String msg = onlyServiceAPI.save(key, Oprator.getUserId());
|
||||
SecurityUtils.removeUserSession();
|
||||
OnFile fileInfo = new OnFile();
|
||||
fileInfo.setFileId(id);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.oo.demo.controller;
|
||||
|
||||
import com.oo.demo.service.WebSocketServer;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Controller("web_Socket_system")
|
||||
@RequestMapping("/socket")
|
||||
public class WebSocketController {
|
||||
//页面请求
|
||||
@GetMapping("/index/{userId}")
|
||||
public ModelAndView socket(@PathVariable String userId) {
|
||||
ModelAndView mav = new ModelAndView("/socket1");
|
||||
mav.addObject("userId", userId);
|
||||
return mav;
|
||||
}
|
||||
//推送数据接口
|
||||
@ResponseBody
|
||||
@RequestMapping("/push/{cid}")
|
||||
public Map pushToWeb(@PathVariable String cid, String message) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
WebSocketServer.sendInfo(message, cid);
|
||||
result.put("code", cid);
|
||||
result.put("msg", message);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import org.apache.ibatis.annotations.Mapper;
|
||||
* Mapper 接口
|
||||
* </p>
|
||||
*
|
||||
*
|
||||
* @author tonghui
|
||||
* @since 2022-03-10
|
||||
*/
|
||||
@Mapper
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
package com.oo.demo.entity;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @BelongsProject: leaf-onlyoffice
|
||||
* @BelongsPackage: com.ideayp.leaf.entity
|
||||
* @Author: TongHui
|
||||
* @CreateTime: 2022-11-14 10:20
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
@@ -32,6 +25,7 @@ public class OnFile {
|
||||
private String fileName;
|
||||
private String fileType;
|
||||
private String filePath;
|
||||
private String caseId;
|
||||
private Long fileSize;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.oo.demo.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @BelongsProject: leaf-onlyoffice
|
||||
* @BelongsPackage: com.ideayp.leaf.entity
|
||||
* @CreateTime: 2022-11-14 10:20
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WebsocketResult {
|
||||
private OnFile onFile;
|
||||
private String userId;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.util.Map;
|
||||
/**
|
||||
* @BelongsProject: onlyoffice-demo
|
||||
* @BelongsPackage: com.oo.demo.service
|
||||
* @Author: TongHui
|
||||
*
|
||||
* @CreateTime: 2023-08-01 16:00
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
|
||||
@@ -1,26 +1,24 @@
|
||||
package com.oo.demo.service;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.oo.demo.entity.OnFile;
|
||||
import com.oo.demo.entity.WebsocketResult;
|
||||
import com.oo.onlyoffice.api.OnlyServiceAPI;
|
||||
import com.oo.onlyoffice.dto.edit.FileUser;
|
||||
import com.oo.onlyoffice.tools.SecurityUtils;
|
||||
import com.oo.demo.entity.Result;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
//import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @BelongsProject: onlyoffice-demo
|
||||
* @BelongsPackage: com.oo.demo.service
|
||||
* @Author: TongHui
|
||||
* @CreateTime: 2023-08-02 09:57
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
@@ -41,51 +39,48 @@ public class FileService {
|
||||
* @param jsonObject
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Object documentSave(JSONObject jsonObject) {
|
||||
JSONObject result = new JSONObject();
|
||||
public WebsocketResult documentSave(JSONObject jsonObject) {
|
||||
WebsocketResult result = new WebsocketResult();
|
||||
String key = "";
|
||||
try {
|
||||
int status = jsonObject.getIntValue("status");
|
||||
log.info("status[{}]", status);
|
||||
if (6 == status) {
|
||||
log.info("开始保存文件");
|
||||
|
||||
log.info("dayin:" + JSON.toJSONString(jsonObject));
|
||||
JSONArray jsonArray = jsonObject.getJSONObject("history").getJSONArray("changes");
|
||||
log.info("历史版本:" + JSON.toJSONString(jsonArray));
|
||||
JSONObject object = jsonArray.getJSONObject(0);
|
||||
String userId = object.getJSONObject("user").getString("id");
|
||||
FileUser fileUser = new FileUser();
|
||||
fileUser.setId(userId);
|
||||
SecurityUtils.setUserSession(fileUser);
|
||||
|
||||
log.info("fileuser:" + JSON.toJSONString(fileUser));
|
||||
key = jsonObject.getString("key");
|
||||
|
||||
log.info("key:" + JSON.toJSONString(key));
|
||||
//文件id
|
||||
String id = onlyServiceAPI.getFileId(key);
|
||||
|
||||
|
||||
String fileId = onlyServiceAPI.getFileId(key);
|
||||
log.info("fileId:" + JSON.toJSONString(fileId));
|
||||
//判断是否是最后一人进行保存
|
||||
int users = onlyServiceAPI.getUserNum(key);
|
||||
if (users > 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// if (users > 1) {
|
||||
// return null;
|
||||
// }
|
||||
//历史版本最大个数 获取当前文件的历史版本数量
|
||||
Integer histNum = onlyServiceAPI.getHistNum();
|
||||
log.info("历史版本最大个数" + histNum);
|
||||
/**
|
||||
* 如果有需要保存历史记录 可以进行相关操作
|
||||
*/
|
||||
if (null != histNum) {
|
||||
|
||||
}
|
||||
|
||||
//处理文件的保存
|
||||
onlyServiceAPI.handlerStatus(jsonObject);
|
||||
|
||||
|
||||
OnFile file = onlyServiceAPI.handlerStatus(jsonObject);
|
||||
result = WebsocketResult.builder().onFile(file).userId(SecurityUtils.getUserSession().getId()).build();
|
||||
log.info("处理文件的保存:" + JSON.toJSONString(jsonObject));
|
||||
log.info("保存文件结束");
|
||||
SecurityUtils.removeUserSession();
|
||||
result.put("key", key);
|
||||
result.put("fileId", id);
|
||||
return result;
|
||||
} else if (0 == status || 2 == status || 4 == status) {
|
||||
onlyServiceAPI.close(jsonObject);
|
||||
@@ -108,7 +103,7 @@ public class FileService {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
result.put("key", key);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,5 +13,12 @@ public interface OnFileService extends IService<OnFile> {
|
||||
|
||||
void removeFile(String id);
|
||||
|
||||
void download(String id,String isBrowser, HttpServletResponse response);
|
||||
void download(String id, String isBrowser, HttpServletResponse response);
|
||||
|
||||
/**
|
||||
* 根据文件id查找文件信息
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
OnFile getFileById(String id);
|
||||
}
|
||||
|
||||
@@ -7,14 +7,12 @@ import com.oo.demo.dao.OnFileMapper;
|
||||
import com.oo.demo.entity.OnFile;
|
||||
import com.oo.onlyoffice.tools.FileUtil;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.file.Files;
|
||||
|
||||
|
||||
/**
|
||||
@@ -22,7 +20,6 @@ import java.nio.file.Files;
|
||||
* 服务实现类
|
||||
* </p>
|
||||
*
|
||||
*
|
||||
* @since 2022-03-10
|
||||
*/
|
||||
@Service
|
||||
@@ -42,6 +39,12 @@ public class OnFileServiceImpl extends ServiceImpl<OnFileMapper, OnFile> impleme
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OnFile getFileById(String id) {
|
||||
OnFile file = baseMapper.selectById(id);
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeFile(String id) {
|
||||
OnFile byId = baseMapper.selectById(id);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.oo.demo.service;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @BelongsProject: onlyoffice-demo
|
||||
* @BelongsPackage: com.oo.demo.service
|
||||
* @CreateTime: 2023-08-05 17:14
|
||||
* @Description: TODO
|
||||
* @Version: 1.0
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class Oprator {
|
||||
private static Logger logger = LoggerFactory.getLogger(Oprator.class);
|
||||
private static List<Map<String, String>> cache1 = new ArrayList<>();
|
||||
private static Integer index;
|
||||
|
||||
static {
|
||||
for (int i = 0; i < 1; i++) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
// map.put("userId", IdUtil.simpleUUID().substring(0,6));
|
||||
// map.put("userName","TongHui"+map.get("userId"));
|
||||
map.put("userId", "0");
|
||||
map.put("userName", "OnlyOfficeUser1");
|
||||
cache1.add(map);
|
||||
}
|
||||
logger.info("用户初始完毕");
|
||||
// Random random = new Random();
|
||||
// index = random.nextInt(10);
|
||||
index = 0;
|
||||
logger.info("获取用户完毕" + index);
|
||||
}
|
||||
|
||||
public static String getUserName() {
|
||||
return cache1.get(index).get("userName");
|
||||
}
|
||||
|
||||
public static String getUserId() {
|
||||
return cache1.get(index).get("userId");
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.oo.demo.service;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @BelongsProject: onlyoffice-demo
|
||||
* @BelongsPackage: com.oo.demo.service
|
||||
* @Author: TongHui
|
||||
* @CreateTime: 2023-08-05 17:14
|
||||
* @Description: TODO 用户信息
|
||||
* @Version: 1.0
|
||||
*/
|
||||
public class TempUser {
|
||||
private static Logger logger = LoggerFactory.getLogger(TempUser.class);
|
||||
private static List<Map<String,String>> cache1 = new ArrayList<>();
|
||||
private static Integer index;
|
||||
|
||||
static {
|
||||
for (int i = 0; i < 1; i++) {
|
||||
Map<String,String> map = new HashMap<>();
|
||||
map.put("userId", "1");
|
||||
map.put("userName","OnlyOfficeUserName"+map.get("userId"));
|
||||
cache1.add(map);
|
||||
}
|
||||
logger.info("用户初始完毕");
|
||||
Random random = new Random();
|
||||
// index = random.nextInt(10);
|
||||
index = 0;
|
||||
logger.info("获取用户完毕"+index);
|
||||
}
|
||||
public static String getUserName(){
|
||||
return cache1.get(index).get("userName");
|
||||
}
|
||||
public static String getUserId(){
|
||||
return cache1.get(index).get("userId");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.oo.demo.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.websocket.*;
|
||||
import javax.websocket.server.PathParam;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
/**
|
||||
* @ Description:
|
||||
* @ ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
|
||||
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
|
||||
* @author ym
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@Service
|
||||
@ServerEndpoint("/api/websocket/{userid}")
|
||||
public class WebSocketServer {
|
||||
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
|
||||
private static int onlineCount = 0;
|
||||
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
|
||||
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
|
||||
|
||||
//与某个客户端的连接会话,需要通过它来给客户端发送数据
|
||||
private Session session;
|
||||
|
||||
//接收userid
|
||||
private String userid = "";
|
||||
|
||||
/**
|
||||
* 连接建立成功调用的方法
|
||||
*/
|
||||
@OnOpen
|
||||
public void onOpen(Session session, @PathParam("userid") String userid) {
|
||||
this.session = session;
|
||||
webSocketSet.add(this); //加入set中
|
||||
this.userid = userid;
|
||||
addOnlineCount(); //在线数加1
|
||||
try {
|
||||
sendMessage("conn_success");
|
||||
log.info("有新窗口开始监听:" + userid + ",当前在线人数为:" + getOnlineCount());
|
||||
} catch (IOException e) {
|
||||
log.error("websocket IO Exception");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接关闭调用的方法
|
||||
*/
|
||||
@OnClose
|
||||
public void onClose() {
|
||||
//从set中删除
|
||||
webSocketSet.remove(this);
|
||||
//在线数减1
|
||||
subOnlineCount();
|
||||
//断开连接情况下,更新主板占用情况为释放
|
||||
log.info("释放的userid为:" + userid);
|
||||
//这里写你 释放的时候,要处理的业务
|
||||
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到客户端消息后调用的方法
|
||||
*
|
||||
* @ Param message 客户端发送过来的消息
|
||||
*/
|
||||
@OnMessage
|
||||
public void onMessage(String message, Session session) {
|
||||
log.info("收到来自窗口" + userid + "的信息:" + message);
|
||||
//群发消息
|
||||
for (WebSocketServer item : webSocketSet) {
|
||||
try {
|
||||
item.sendMessage(message);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ Param session
|
||||
* @ Param error
|
||||
*/
|
||||
@OnError
|
||||
public void onError(Session session, Throwable error) {
|
||||
log.error("发生错误");
|
||||
error.printStackTrace();
|
||||
}
|
||||
|
||||
/**
|
||||
* 实现服务器主动推送
|
||||
*/
|
||||
public void sendMessage(String message) throws IOException {
|
||||
this.session.getBasicRemote().sendText(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 群发自定义消息
|
||||
*/
|
||||
public static void sendInfo(String message, @PathParam("userid") String userid) throws IOException {
|
||||
log.info("推送消息到窗口" + userid + ",推送内容:" + message);
|
||||
|
||||
for (WebSocketServer item : webSocketSet) {
|
||||
try {
|
||||
//这里可以设定只推送给这个userid的,为null则全部推送
|
||||
if (userid == null) {
|
||||
// item.sendMessage(message);
|
||||
} else if (item.userid.equals(userid)) {
|
||||
item.sendMessage(message);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized int getOnlineCount() {
|
||||
return onlineCount;
|
||||
}
|
||||
|
||||
public static synchronized void addOnlineCount() {
|
||||
WebSocketServer.onlineCount++;
|
||||
}
|
||||
|
||||
public static synchronized void subOnlineCount() {
|
||||
WebSocketServer.onlineCount--;
|
||||
}
|
||||
|
||||
public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
|
||||
return webSocketSet;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user