最近在做的项目中客户有监控软件的需求。

需求:每5秒显示被监控电脑的桌面情况。

实现思路:

1.截图端:Timer每5秒截图、调用服务端接口上传。

2.服务端:保存截图到服务端本地并把截图信息保存到数据库,包括图片在服务端的保存路径。

3.监控端:①调用服务端下载List<ScreenShot>接口,下载需要显示的截图列表。②Timer每5秒调用服务端下载最新ScreenShot对象,加入监控端list<ScreenShot>中。③要显示某张截图时根据本地List<ScreenShot>中信息调用服务端下载截图接口把截图下载到本地并显示在pictureBox中,下载成功则把ScreenShot对象中isDownload属性标为true,一遍下次直接调用,避免重复下。

 

一、截图端

1.实现截屏功能。



//截屏
        private void timerPrtSc_Tick(object sender, EventArgs e)
        {
                   //定义一个矩形  
            Rectangle rect = new Rectangle();
            //该矩形大小为当前屏幕大小
            rect = System.Windows.Forms.Screen.GetBounds(this);
            //定义Size类型,取得矩形的长和宽
            Size mySize = new Size(rect.Width, rect.Height);
            //定义一个位图,长宽等于屏幕长宽
            Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
            //定义Graphics为了在bitmap上绘制图像
            Graphics g = Graphics.FromImage(bitmap);
            //把mySize大小的屏幕绘制到Graphisc上
            g.CopyFromScreen(0, 0, 0, 0, mySize);
            //创建文件路径
            string ImageName = DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png";
            string dir = @"./upload/";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string filePath = dir + ImageName;
            //保存文件到本地
            bitmap.Save(filePath);
            //上传文件到服务器
            HttpPostData(R.URL, R.TimeOut, R.MultipartFile, filePath);
            //释放资源  
            bitmap.Dispose();
            g.Dispose();
            GC.Collect();
        }



 

2.上传文件到服务器(模拟表单提交把要传送的文件转换成流post到服务器中)



/// <summary>
        /// 模拟表单Post数据(传送文件以及参数)到Java服务端
        /// </summary>
        /// <param name="url">服务端url地址</param>
        /// <param name="timeOut">响应时间</param>
        /// <param name="fileKeyName">对应接口中    @RequestParam("file"),fileKeyName="file"</param>
        /// <param name="filePath">要上传文件在本地的全路径</param>
        /// <returns></returns>
        /// 
        private string HttpPostData(string url, int timeOut, string fileKeyName, string filePath)
        {
            //stringDict为要传递的参数的集合
            NameValueCollection stringDict = new NameValueCollection();
            stringDict.Add("ip", ip);
            stringDict.Add("user", program.UserId);
            stringDict.Add("programId", program.ProgramId);

            string responseContent=string.Empty;
            //创建其支持存储区为内存的流
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件(以下字符串中name值对应接口中@RequestParam("file"),fileName为上传文件在本地的全路径)
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();
            return responseContent;
        }



 

二、Java服务端

1.服务端上传接口



/**
     * 上传截屏
     * @param ip
     * @param filename
     * @return
     */    
    @RequestMapping(value="upload",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, String> upload( 
            @RequestParam("ip") String ip,
            @RequestParam("user") String user,
            @RequestParam("programId") String programId,
            @RequestParam("file") MultipartFile file
            ){
        
        Map<String, String> result = new HashMap<String, String>();
        logger.info("file name " + file.getOriginalFilename());
        ScreenShot ss=screenShotService.upload(ip.trim(), user.trim(), programId.trim(), file);
        result.put("ip", ss.getId());
        result.put("user", ss.getUser());
        result.put("channel", ss.getProgramId());
        result.put("localpath", ss.getLocalPath());
        return result;
    }



 



/**
     * 上传截屏
     * 
     * 逻辑:
     * 1,把文件转移到存储目录
     * 2,生成screenshot对象保存起来
     * @param ip 
     * @param filename
     */
    public ScreenShot upload(String userIP,String userName,String programid, MultipartFile file)
    {
        
        try {
            String ip=userIP;
            String user=userName;
            String programId=programid;
            String localPath = receiveFile(file);
            Long timeStamp=System.currentTimeMillis();
            if (StringUtils.isNotBlank(localPath)){
                //创建对象
                ScreenShot ss = new ScreenShot(file.getOriginalFilename(),ip,user,programId,localPath,timeStamp);
                //保存到数据库
                ss = screenShotRepository.save(ss);
                return ss;
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    private String receiveFile(MultipartFile file) throws IOException {
        String path;        
        //destPath为存储文件的目录地址,目录下文件夹和文件取名由ileUtil.buildNewFileName()完成
        String destPath = FileUtil.buildNewFileName(configService.getUploadRootPath() + Const._SPLASH, file.getOriginalFilename());
        logger.info("upload file Path is " + file.getOriginalFilename() 
                + " dest file name is " + destPath);
        //新建一个名为dest的空文件
        File dest = new File(destPath);
        //把file放到dest的path
        file.transferTo(dest);
        path = dest.getPath();
        return path;
    }



 

2.服务端下载List<ScreenShot>接口



/**
     * 返回节目开始至当前时间点的List<ScreenShot>
     * @param timeStamp
     * @param ip
     * @return
     */
    @RequestMapping (value = "searchList")
    @ResponseBody
    public Map<String,Object> searchList(
            @RequestParam( value = "ip", defaultValue="" ) String ip,
            @RequestParam( value = "startId", defaultValue="" ) String startId,
            //@PathVariable("ip")        String ip,         @PathVariable路径变量
            //@PathVariable("startId") String startId      @RequestParam请求参数
            HttpServletRequest request)
    {
        
        List<ScreenShot> ss = this.screenShotService.findListByIpandID(ip,startId);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("rows", ss);
        return map;
    }



 

3.服务端下载ScreenShot对象接口



/**
     * 返回当前时间点的ScreenShot
     * @param ip
     * @return
     */
    @RequestMapping (value = "searchCurrent")
    @ResponseBody
    public ScreenShot searchCurrent(
            @RequestParam( value = "ip", defaultValue="" ) String ip,
            @RequestParam( value = "currentId", defaultValue="" ) String currentId)
    {
        ScreenShot ss = this.screenShotService.findOneById(ip,currentId);
        return ss;
    }



 

4.服务端根据id下载文件接口



/**
     * 下载id对应的截屏
     */
    @RequestMapping (value = "download/{id}")
    @ResponseBody
    public void download(
            @PathVariable("id")        String id,
            HttpServletRequest            request,
            HttpServletResponse            response)
    {
          try {
                response.setContentType("text/html;charset=UTF-8");
                request.setCharacterEncoding( Const._UTF8 );
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                
                ScreenShot ss = this.screenShotService.findById(id);
                
                
                String localPath =ss.getLocalPath();
                
                response.setContentType("application/octet-stream");
    
                String downloadName = ss.getFileName();
                String extention = "png"; 
                response.setHeader("extension",extention);
                response.setHeader("downloadName",downloadName );
            
                String agent = request.getHeader("USER-AGENT");
                if (null != agent && -1 != agent.indexOf("MSIE")) { // IE内核浏览器
                    downloadName = new String(downloadName.getBytes(), "ISO8859-1");
                    downloadName = URLEncoder.encode(downloadName, Const._UTF8 );
                    downloadName = new String(downloadName.getBytes( Const._UTF8 ), "ISO8859-1");
                    downloadName = downloadName.replace("+", "%20");// 处理IE文件名中有空格会变成+"的问题;
                } else {// 非IE
                    downloadName = URLDecoder.decode(downloadName, Const._UTF8);
                    downloadName = "=?UTF-8?B?"
                            + (new String(Base64.encodeBase64(downloadName.getBytes( Const._UTF8 )))) 
                            + "?=";
                }
                response.setHeader("Content-disposition", "attachment; filename=" + downloadName);
                
                bis = new BufferedInputStream(new FileInputStream( localPath ));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
                bis.close();
                bos.close();  
                
            } catch (Exception e) {
                e.printStackTrace();
            }
    }



三、监控端

1.调用服务端下载接口下载List<ScreenShot>



//保存服务器下载的ScreenShot列表
        private List<ScreenShot> listScreenShot = new List<ScreenShot>();
        /// <summary>
        /// 下载节目开始至当前时间点的List<ScreenShot>
        /// </summary>
        /// <param name="ip">njmonitor客户端PC机的ip</param>
        /// <param name="startId">当前节目开始的id号</param>
        /// <returns></returns>
        public List<ScreenShot> DownloadList(string ip, string startId)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            List<ScreenShot> ss = new List<ScreenShot>();
            string url = "monit/searchList?ip={ip}&startId={startId}";
            parameters.Add("ip", ip);
            parameters.Add("startId", startId);
            RestResponse response = HttpClient.RequestResponse("radionav", url, "get", parameters);
            OpResult result = null;

            if (!response.StatusCode.Equals(System.Net.HttpStatusCode.OK))
            {
                result = new OpResult();
                result.Ok = false;
                result.Reason = response.ErrorMessage;
            }
            else
            {
                string content = response.Content;
                try
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(content);
                    object[] obj = (object[])json["rows"];
                    //遍历数组

                    for (int i = 0; i < obj.Length; i++)
                    {
                        //object对象内又为dictionary,转为DICTIONARY对象
                        Dictionary<string, object> jsonScreenShot = (Dictionary<string, object>)obj[i];
                        //传入screenshot类
                        ScreenShot screenShot = new ScreenShot(jsonScreenShot);
                        ss.Add(screenShot);
                    }

                }
                catch (Exception e)
                {
                    result = new OpResult(false, null);
                }
            }
            return ss;
        }



 

2.调用服务端下载接口下载截屏



public static string GetUrlDownContent(string url, string path)
        {
            string localPath = string.Empty;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();

                string downloadName = myrp.Headers["downloadName"];
                localPath = path + downloadName;

                System.IO.Stream so = new System.IO.FileStream(localPath, System.IO.FileMode.Create);
                System.IO.Stream st = myrp.GetResponseStream();
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }

                so.Close();
                st.Close();

                myrp.Close();
                Myrq.Abort();
   

                return localPath;
            }
            catch (System.Exception e)
            {
                return null;
            }
        }