/// <summary> /// 上传文件 /// </summary> private void UploadRegularloadFile(Socket socketClient, int year, int categoryId) { string filePath = MSExcelTools.DEFAULT_REGULARLOAD_FILE(year, categoryId); // 如果计划额度表已经存在则直接下载即可 // 计划文件的下载地址 //string regularloadFilePath = MSExcelTools.DEFAULT_REGULARLOAD_FILE(year, categoryId); //if (File.Exists((String)regularloadFilePath) == true) // 首先检测文件是否存在 //{ // Console.WriteLine("计划额度表{0}文件存在, 需要修改", regularloadFilePath); // filePath = regularloadFilePath; //} //else //{ // return; //} Console.WriteLine("开始上传文件"); // UPLOAD_PICTURE_REQUEST;2;30;length;byte // 取出后的结果为 // 0 UPLOAD_PICTURE_REQUEST // 1 2 // 2 30 // 因为终端每次发送文件的最大缓冲区是512字节,所以每次接收也是定义为512字节 byte[] buffer = new byte[1024 * 1024]; //int size = split[3].Length; int size = 0; long len = 0; //string filePath = MSExcelTools.DEFAULT_REGULARLOAD_PATH + year.ToString() + categoryId.ToString() + "regularload.xls"; //获得用户保存文件的路径 Console.WriteLine("文件的存储路径" + filePath); //创建文件流,然后让文件流来根据路径创建一个文件 FileStream fs = new FileStream(filePath, FileMode.Create); Console.WriteLine("开始写入文件"); //fs.Write(message, 0, size); //Byte msg = Encoding.UTF8.GetBytes(split[3]); //fs.Write(split[3], 0, size); //len += size; //从终端不停的接受数据,然后写入文件里面,只到接受到的数据为0为止,则中断连接 while ((size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0) { fs.Write(buffer, 0, size); len += size; } Console.WriteLine("开始写入文件,共{0}个字节", len); fs.Flush(); fs.Close(); //dict.Remove(socketClient.RemoteEndPoint.ToString()); //socketClient.Close(); }
/// <summary> /// 下载会签单计划额度分配表模版 /// </summary> /// <param name="socketClient"></param> /// <param name="categoryId"></param> private void DownloadingRegularloadTemplateFile(Socket socketClient, int year, int categoryId) { string filePath = ""; // 如果计划额度表已经存在则直接下载即可 // 计划文件的下载地址 string regularloadFilePath = MSExcelTools.DEFAULT_REGULARLOAD_FILE(year, categoryId); if (File.Exists((String)regularloadFilePath) == true) // 首先检测文件是否存在 { Console.WriteLine("计划额度表{0}文件存在, 直接下载", regularloadFilePath); filePath = regularloadFilePath; } else { Console.WriteLine("计划额度表{0}文件不存在, 需要下载模版表", regularloadFilePath); string regularTemplateFilePath = MSExcelTools.DEFAULT_REGULARLOAD_TEMPLATE_FILE(categoryId); if (File.Exists((String)regularTemplateFilePath) == true) // 首先检测文件是否存在 { Console.WriteLine("计划额度模版{0}文件存在, 可以下载", regularTemplateFilePath); filePath = regularTemplateFilePath; } else { Console.WriteLine("计划模版{0}文件不存在, 下载失败", regularTemplateFilePath); return; } } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read); Console.WriteLine("开始下载文件{0}, 文件大小{1}", filePath, fs.Length); // 先发送文件大小 socketClient.Send(System.Text.Encoding.Unicode.GetBytes(fs.Length.ToString())); // 再发送文件信息 byte[] fssize = new byte[fs.Length]; BinaryReader reader = new BinaryReader(fs); reader.Read(fssize, 0, fssize.Length - 1); socketClient.Send(fssize); fs.Flush(); fs.Close(); Console.WriteLine("下载文件结束"); }
/// <summary> /// 下载会签单信息文件 /// </summary> private void DownloadingStatisticFile(Socket socketClient, int year, int categoryId) { // 首先生成会签单信息 //ContractCategory category = DALContractIdCategory.GetCategory(categoryId); //String filePath = MSExcelTools.DEFAULT_STATISTIC_PATH + year +category.Category + ".xls"; //Console.WriteLine("统计能申请当前Id = {0}, Category = {1}信息", category.Id, category.Category); //if (File.Exists((String)filePath) == true) // 首先检测文件是否存在 //{ // File.Delete((String)filePath); //} //String excelFilePath = MSExcelTools.StatisticYearCategory(year, categoryId); String excelFilePath = MSExcelTools.DEFAULT_STATISTIC_FILE(year, categoryId); if (File.Exists((String)excelFilePath) == false) // 首先检测文件是否存在 { Console.WriteLine("统计表{0}不存在, 无法下载", excelFilePath); return; } //MSExcelTools.KillExcelProcess(); // 开始下载文件 FileStream fs = new FileStream(excelFilePath, FileMode.OpenOrCreate, FileAccess.Read); Console.WriteLine("开始下载文件{0}, 文件大小{1}", excelFilePath, fs.Length); // 先发送文件大小 socketClient.Send(System.Text.Encoding.Unicode.GetBytes(fs.Length.ToString())); // 再发送文件信息 byte[] fssize = new byte[fs.Length]; BinaryReader reader = new BinaryReader(fs); reader.Read(fssize, 0, fssize.Length - 1); socketClient.Send(fssize); fs.Flush(); fs.Close(); Console.WriteLine("下载文件结束"); //dict.Remove(socketClient.RemoteEndPoint.ToString()); //socketClient.Close(); }
/// <summary> /// 接收消息 /// 如果是上传签字图片,则数据格式为[报头 + id + 图片信息流] /// 如果是下载会签单信息,则数据格式为[报头 + 编号] /// </summary> /// <param name="socketClientPara"></param> private void RecMsg(object socketClientPara) { Socket socketClient = socketClientPara as Socket; byte[] recvBuffer = new byte[512]; // SocketMessage message = new SocketMessage(); // modify by gatieme 205-07-04 12:44 // 正常来说线程执行完毕以后,应该自行终止, // 但是由于之前这个使用了while循环的错误方式, // 导致用户上传下载签字图片,或者下载会签单信息后,线程一直在跑,未中断 // 导致服务器的CPU占有率达到100% //while (true) //{ //定义一个接受用的缓存区(100M字节数组) //byte[] arrMsgRec = new byte[1024 * 1024 * 100]; //将接收到的数据存入arrMsgRec数组,并返回真正接受到的数据的长度 if (socketClient.Connected) { Console.WriteLine("开始传输文件"); try { // 首先接收到信息头,确定是要上传还是下载,以及文件的编号信息 socketClient.Receive(recvBuffer, 0, 300, SocketFlags.None); String message = Encoding.UTF8.GetString(recvBuffer); Console.WriteLine("大小{0},{1}", message.Length, message); string[] split = message.Split('~'); //返回由'/'分隔的子字符串数组 Console.WriteLine("LENGTH : {0}", split.Length); String id = split[2]; //int pos = message.LastIndexOf(';'); //Byte[] picture = new Byte[1024]; //recvBuffer.CopyTo(picture, pos + 1); //Console.WriteLine(picture.ToString()); switch (split[0]) { /// 签字图片的上传和下载 // UPLOAD_PICTURE_REQUEST;2;30 case "UPLOAD_PICTURE_REQUEST": // 用户上传签字图片 { UploadFile(socketClient, id); break; } case "DOWNLOAD_PICTURE_REQUEST": // 用户下载签字图片 { String empId = JsonConvert.DeserializeObject <String>(id); DownloadSignatureFile(socketClient, empId); break; } /// 会签单的下载 case "DOWNLOAD_HDJCONTRACT_REQUEST": // 用户下载会签单 { String conId = JsonConvert.DeserializeObject <String>(id); DownloadContractFile(socketClient, conId); break; } /// 上传计划额度表模版 case "UPLOAD_REGULARLOAD_REQUEST": { // 传送year + id 即可 Search search = JsonConvert.DeserializeObject <Search>(id); UploadRegularloadFile(socketClient, search.Year, search.CategoryId); // 开始接收文件 ///// 此处有性能问题,最后能交给MSOfficeThread来完成这个工作 // 接收完毕后将数据插入到数据库中 // BUG BUG // 先删除数据库里面的计划额度表信息 DALContractRegularoload.DeleteYearCategoryRegularload(search.Year, search.CategoryId); // 再将excel中的数据插入到数据库中 MSExcelTools.UploadRegularLoad(search.Year, search.CategoryId); break; } // 统计报表的下载 case "DOWNLOAD_STATISTIC_REQUEST": { Search search = JsonConvert.DeserializeObject <Search>(id); DownloadStatisticFile(socketClient, search.Year, search.CategoryId); break; } // 下载计划额度表模版 case "DOWNLOAD_REGULARLOAD_REQUEST": { // 传送id即可 Search search = JsonConvert.DeserializeObject <Search>(id); DownloadRegularloadTemplateFile(socketClient, search.Year, search.CategoryId); break; } // 统计报表的下载 -=> 为了适应安卓的下载 case "DOWNLOADING_STATISTIC_REQUEST": { Search search = JsonConvert.DeserializeObject <Search>(id); DownloadingStatisticFile(socketClient, search.Year, search.CategoryId); break; } // 下载计划额度表模版 -=> 为了适应安卓的下载 case "DOWNLOADING_REGULARLOAD_REQUEST": { // 传送id即可 Search search = JsonConvert.DeserializeObject <Search>(id); DownloadingRegularloadTemplateFile(socketClient, search.Year, search.CategoryId); break; } } dict.Remove(socketClient.RemoteEndPoint.ToString()); socketClient.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } else { /// 客户端未正常连接 Console.WriteLine("文件传输客户端未正常连接自文件服务器"); } }
static void Main(string[] args) { Console.WriteLine("====================="); Console.WriteLine("SignPressServer BUILD-0002"); Console.WriteLine("====================="); Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory); Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //Console.WriteLine(System.DateTime.Now.ToString("yyyyMMddHHmmss")); //string contractId = "佳内2015001"; //Console.Write(DALHDJContract.GetDepartmentShortCallFromContractId(contractId)); //Console.Write(DALHDJContract.GetCatgoryShortCallFromContractId(contractId)); //Console.Write(DALHDJContract.GetYearFromContractId(contractId)); //Console.Write(DALHDJContract.GetIsOnlineFromContractId(contractId)); //Console.Write(DALHDJContract.GetNumFromContractId(contractId)); //获取当前进程的完整路径,包含文件名(进程名)。 //Console.WriteLine(this.GetType().Assembly.Location); //result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名) //获取新的Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。 //Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); //result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名) //获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。 //Console.WriteLine(System.Environment.CurrentDirectory); //result: X:\xxx\xxx (.exe文件所在的目录) //获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。 //Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory); //result: X:\xxx\xxx\ (.exe文件所在的目录+"\") //获取和设置包含该应用程序的目录的名称。 //Console.WriteLine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase); //result: X:\xxx\xxx\ (.exe文件所在的目录+"\") //获取应用程序的当前工作目录(不可靠)。 //Console.WriteLine(System.IO.Directory.GetCurrentDirectory()); //result: X:\xxx\xxx (.exe文件所在的目录) /// 测试连接服务器以及查询测试 //int currDayConCount = DALHDJContract.GetDayHDJContractCount(System.DateTime.Now.Date); //Console.WriteLine(System.DateTime.Now.ToString("yyyyMMdd") + (currDayConCount + 1).ToString().PadLeft(6, '0')); #region 测试正则表达式 // String[] text = { "username/password@//myserver:1521/my.service.com", // "username/password@myserver//instancename", // "username/password@myserver/myservice:dedicated/instancename"}; // //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\S*)/(\S*)", RegexOptions.None); // text1 // //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\d*|/)/(\S*)", RegexOptions.None); // text1 // //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\d*|/*)/(\S*)", RegexOptions.None); // text1 // // 在第二个串中@后的`/`可省, myserver:1521中的:port也可以缺省, // //Regex regex = new Regex(@"\S*/\S*@/*(\S*)[:*(\S*) | (/*)]/{1,2}(\S*)", RegexOptions.None); // text1 + text2 // //Regex regex = new Regex(@"\S*/\S*@/*(\w*)(:*)(\d*)/*(\S*)", RegexOptions.None); // text1 + text2 // // 在第三个串中, //// Regex regex = new Regex(@"\S*/\S*(@/{0,2})(\w*)(:*)(\d*)/*(\S*)(:*)(\S*)/(\S*)", RegexOptions.None); // text1 + text2 // Regex regex = new Regex(@"\S*/\S*(@/{0,2})(\w*):*(\d*)/*\S*:*\S*/(\S*)", RegexOptions.None); // text1 + text2 // //Console.WriteLine(text1); // for(int i = 0; i < 3; i++) // { // MatchCollection matchCollection = regex.Matches(text[i]); // Console.WriteLine("Count = " + matchCollection.Count); // for (int j = 0; j < matchCollection.Count; j++) // { // Match match = matchCollection[j]; // Console.WriteLine("Match[{0}]========================", j); // for (int k = 0; k < match.Groups.Count; k++) // { // Console.WriteLine("Groups[{0}]={1}", k, match.Groups[k].Value); // } // } // } #endregion #region 测试数据库连接 // 测试查询工作量信息集合item //List<ContractItem> items = DALContractItem.QueryProjectItem(1); //foreach (ContractItem item in items) //{ // Console.WriteLine(item.Id + ", " + item.ProjectId + ", " + item.Item); //} #endregion #region Word操作 //Start Word and create a new document. /* * 首先添加COM组件Office, * 然后添加.Net组件引用Microsoft.Office.Interop.Word; * 接着添加如下的代码 * using Office; * using Microsoft.Office.Interop.Word; * using Word = Microsoft.Office.Interop.Word; */ /// 对word的操作信息 // 将一个创建的WORD保存为PDF //MSWordTools.WordConvertToPdf(@"G:\[B]CodeRuntimeLibrary\[E]GitHub\\测试文档.doc", // @"G:\[B]CodeRuntimeLibrary\[E]GitHub\测试文档.pdf"); 将一个创建的WORD保存为PDF //String filePath = MSWordTools.DEFAULT_HDJCONTRACT_PATH + "20150712000005.pdf"; //if (!(File.Exists((String)filePath))) // 首先检测文件是否存在 //{ // MSWordTools.KillWordProcess(); // String wordPath = MSWordTools.DEFAULT_HDJCONTRACT_PATH + "20150712000005.doc"; // HDJContract contract = DALHDJContract.GetHDJContactAgree("20150712000005"); // 获取待生成的会签单信息 // MSWordTools.CreateHDJContractWordWithReplace(contract, wordPath); // MSWordTools.WordConvertToPdf(wordPath, filePath); // File.Delete((String)wordPath); // MSWordTools.KillWordProcess(); //} //else //{ // Console.WriteLine("文件存在无需在生成"); //} //MSWordTools.WordConvertToPdf(); //MSExcelTools.Test(); #endregion #region 测试JSON数据 //Action<object> log = o => Console.WriteLine(o); // var e1 = new Employee // { // Id = 1, // Name = "成坚", // Position = "科长", // Department = new Department { Id = 1, Name = "申请科" }, // CanSubmit = true, // CanSign = true, // IsAdmin = true, // User = new User { Username = "******", Password = "******" }, // }; // var e2 = new Employee // { // Id = 1, // Name = "吴佳怡", // Position = "局长", // Department = new Department { Id = 5, Name = "行政科" }, // CanSubmit = true, // CanSign = true, // IsAdmin = true, // User = new User{ Username = "******", Password = "******"}, // }; // e1.Show(); // e2.Show(); // //序列化 参数是要序列化的对象;json是对象序列化后的字符串 // String json = JsonConvert.SerializeObject(new Employee[] { e1, e2 }); // Console.WriteLine(json); // //Employee是目标类型;json是经过Json序列化的对象,字符串形式 // List<Employee> employList = JsonConvert.DeserializeObject<List<Employee>>(json); // JArray ja = JArray.Parse(json); // Console.WriteLine(ja); //注意,格式化过的输出 // foreach (Employee employ in employList) // { // employ.Show(); // } #endregion #region 测试统计的功能 //MSExcelTools.KillExcelProcess(); //MSExcelTools.CreateRegularloadTemplateFile(1); //MSExcelTools.CreateRegularloadTemplateFile(2); //MSExcelTools.CreateRegularloadTemplateFile(3); //MSExcelTools.CreateRegularloadTemplateFile(4); //MSExcelTools.UploadRegularLoad(2016, 2); //DALContractRegularoload.DeleteYearCategoryRegularload(2016, 2); //MSExcelTools.KillExcelProcess(); //MSExcelTools.StatisticHSYearCategory(2016, 1); //MSExcelTools.StatisticHSYearCategory(2016, 2); MSExcelTools.StatisticHSYearCategory(2016, 3); //MSExcelTools.StatisticHSYearCategory(2016, 4); #endregion #region 获取本机的IP //QUERY_UNSIGN_CONTRACT_REQUEST; 1; 1QUERY_SIGN_REFUSE_REQUEST; 1; 1 //QUERY_REQUEST;0; QUERY_SIGN_REFUSE_REQUEST; 1; 1 //QUERY_SIGN_REFUSE_REQUEST;1; 1; QUERY_REQUEST;0 //QUERY_REQUEST;0; QUERY_REQUEST;0 ////string s1 = "QUERY_REQUEST; QUERY_SIGN_REFUSE_REQUEST;1;1;"; // AsyncSocketMessage message = new AsyncSocketMessage(ClientRequest.LOGIN_REQUEST); // message.Package = @"QUERY_UNSIGN_CONTRACT_RE // QUEST11QUERY_SIGN_REFUSE_REQU // EST1QUERY_SIGN_REFUSE_REQUES1"; // // 3 5 7 9 11 // do // { // if (message.Split() == AsyncSocketMessageFlag.MESSAGE_UNKOWN) // 将数据包分割 // { // break; // } // }while(message.Flag != AsyncSocketMessageFlag.MESSAGE_RIGHT); string hostName = System.Net.Dns.GetHostName(); //本机名 System.Net.IPAddress[] addressList = System.Net.Dns.GetHostAddresses(hostName); //会返回所有地址,包括IPv4和IPv6 Console.WriteLine("HOST Name = " + hostName); foreach (System.Net.IPAddress ip in addressList) { Console.WriteLine("IP Address = " + ip.ToString()); } #endregion //for (int row = 6, cnt = 0; row <= 8; row++) // 填写表格的签字人表头 //{ // for (int col = 1; col <= 3; col += 2, cnt++) // { // Console.WriteLine("签字人信息位置{0}, {1} ==== 签字人序号{2} ==== 签字位置{3},{4}", row, col, cnt, row, col + 1); // } //} #region 务器的处理程序AsyncSocketServer Console.WriteLine("服务器准备中..."); const int PORT = 6666; //System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("10.0.209.144"), 6666); AsyncSocketServer server = new AsyncSocketServer(PORT); while (true) { server.Start(); } //SocketTCPServer server = new SocketTCPServer(6666); //server.Start(); #endregion }