private bool SendFileToServer(string filePath) { FileInfo fi = new FileInfo(filePath); if (fi.Length > 4096 * 1024) { throw new Exception("被发送文件大小不能超过4096KB。"); } else if (fi.Length == 0) { throw new Exception("文件大小不能为0。"); } // 头附加数据 MyFileInfo myFile = new MyFileInfo() { FilePath = filePath, FileSize = fi.Length, }; // 发送文件标记,用来在onrecv里判断是否文件回包 isSendFile = true; // 不附加尾数据 bool ret = client.SendSmallFile <MyFileInfo, object>(filePath, myFile, null); if (ret == false) { isSendFile = false; int error = client.SYSGetLastError(); AddMsg(string.Format(" > [SendSmallFile] errorCode:{0}", error)); } return(ret); }
HandleResult OnReceive(IntPtr dwConnId, IntPtr pData, int iLength) { // 数据到达了 if (isSendFile == true) { // 如果发送了文件,并接收到了返回数据 isSendFile = false; MyFileInfo myFile = (MyFileInfo)Marshal.PtrToStructure(pData, typeof(MyFileInfo)); int objSize = Marshal.SizeOf(myFile); // 因为没有附加尾数据,所以大小可以用iLength - objSize byte[] bytes = new byte[iLength - objSize]; Marshal.Copy(pData + objSize, bytes, 0, iLength - objSize); string txt = Encoding.Default.GetString(bytes); string msg = string.Empty; if (txt.Length > 100) { msg = txt.Substring(0, 100) + "......"; } else { msg = txt; } AddMsg(string.Format(" > [{0},OnReceive] -> FileInfo(Path:\"{1}\",Size:{2})", dwConnId, myFile.FilePath, myFile.FileSize)); AddMsg(string.Format(" > [{0},OnReceive] -> FileContent(\"{1}\")", dwConnId, msg)); } else if (studentType != StudentType.None) { byte[] bytes = new byte[iLength]; Marshal.Copy(pData, bytes, 0, iLength); switch (studentType) { case StudentType.Array: Student[] students = client.BytesToObject(bytes) as Student[]; foreach (var stu in students) { AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", dwConnId, stu.Id, stu.Name, stu.GetSexString())); } break; case StudentType.List: List <Student> stuList = client.BytesToObject(bytes) as List <Student>; foreach (var stu in stuList) { AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", dwConnId, stu.Id, stu.Name, stu.GetSexString())); } break; case StudentType.Single: Student student = client.BytesToObject(bytes) as Student; AddMsg(string.Format(" > [{0},OnReceive] -> Student({1},{2},{3})", dwConnId, student.Id, student.Name, student.GetSexString())); studentType = StudentType.None; break; } } else { AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", dwConnId, iLength)); } return(HandleResult.Ok); }