指令帧同步项目的服务器方面比较简单。主要分为两大块,一块是Web服务器,用于检查更新/登录/排行/商城等功能,这里直接使用java springboot实现。另一块是对战服务器,主要用于指令帧转发,后面再提。本文主要复盘Web服务器这块。
一.Web服务器
功能1:过滤统计
首先添加一个过滤器,简单用于统计,没有做登录验证。登陆验证这块按照springboot套路是要用放在interceptor里面。
/**
* 访问过滤器:简单抓取下载访问量
* @author: Dodo
*/
@WebFilter(urlPatterns = "/download/*")
public class AccessFilter implements Filter {
int totalDownload=0;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
totalDownload++;
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("访问信息:"+"IP: " + request.getRemoteAddr()+",URL: " + req.getRequestURI().toString()+"总访问:"+totalDownload);
chain.doFilter(request, response);
}
}
功能2:版本校验与安装包下载
服务器版本检测。简单写个IO,读取服务器中放了最新安装包的文件夹,安装包命名以pack_xxx.apk为模板,通过对比Unity 的版本号与服务器里面的最新安装包的版本号,确定是否要更新文件。这里如果之前的过滤器/拦截器不写登录验证的话很容易被攻击,最好加上。
@RequestMapping("/download")
@Controller
@Slf4j
public class VersionHandle {
private float lastversion;
@GetMapping("/lastVersion")
public ResponseEntity<Map<String, Float>> getLastVersion(){
checklastVersion();
Map<String, Float> response = new HashMap<>();
response.put("lastversion", lastversion);
return ResponseEntity.ok(response);
}
@GetMapping("/apk")
public void downloadFile(HttpServletResponse response) {
checklastVersion();
String filename = "pack_"+lastversion+".apk";
String filePath= "d:\\pack\\"+filename;
Resource resource = new FileSystemResource(filePath);
response.setContentType("application/octet-stream");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
try (InputStream inputStream = resource.getInputStream();
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
} catch (IOException e) {
log.info(e.toString());
}
}
public void checklastVersion(){
try {
File folder = new File("d:/pack");
File[] listOfFiles = folder.listFiles();
Pattern p = Pattern.compile("pack_(\\d+\\.\\d+).apk");
float maxVersion = 0.0f;
for (File file : listOfFiles) {
if (file.isFile()) {
Matcher m = p.matcher(file.getName());
if (m.matches()) {
float version = Float.parseFloat(m.group(1));
if (version > maxVersion) {
maxVersion = version;
}
}
}
}
lastversion = maxVersion;
}catch (Exception e){
log.info(e.toString());
}
}
}