/// <summary> /// 消息接收事件处理程序 /// </summary> /// <param name="tcpComm"></param> /// <param name="msg"></param> void newBlemessageEventFun(tcpDataCommunication tcpComm, stringMsg msg) { switch (msg.name) { case msgEnum.liaotian: liaotian(tcpComm, msg); break; case msgEnum.fileUpload: showMsg(string.Format("收到文件{0}", System.IO.Path.GetFileName(msg.value["saveFileFullPath"]))); bool bl = AddFileInfo(msg); break; case msgEnum.dengru: denglu(tcpComm, msg); break; case msgEnum.getUserFileList: getUserFileList(tcpComm, msg); break; case msgEnum.getDownLandFile: getDownLandFile(tcpComm, msg); break; default: break; } }
void getDownLandFile(tcpDataCommunication tcpComm, stringMsg msg) { string sendFileFullPath = msg.value["sendFileFullPath"]; string saveFileFullPath = msg.value["saveFileFullPath"]; stringMsg returnMsg = new stringMsg(); returnMsg.name = msgEnum.fileUpload; if (File.Exists(sendFileFullPath)) { returnMsg.value.Add("sendFileFullPath", sendFileFullPath); //全路径 returnMsg.value.Add("saveFileFullPath", saveFileFullPath); //全路径 // returnMsg.value.Add("fileDirFullPath", System.IO.Path.GetDirectoryName( clientPath)); // byte[] data = myWebClient.DownloadData(filepath); // string endPath = path + "\\" + CheckFileName(path, folder);//含重名验证,如重名覆盖则改成:path+"\\"+folder // FileStream fs = new FileStream(endPath, FileMode.Create); // fs.Write(data, 0, data.Length); // fs.Close(); // MessageBox.Show("下载成功!", "提示"); // user.UpdateDownLand(filepath); // user.Add_Log_Opera(CurrUser.currUser.ID, CurrUser.currUser.Account, string.Format("下载文件{0}", folder)); } else { returnMsg.value.Add("saveFileFullPath", ""); returnMsg.value.Add("sendFileFullPath", ""); //MessageBox.Show("文件不存在!", "提示"); //user.Add_Log_Error(CurrUser.currUser.ID, CurrUser.currUser.Account, string.Format("下载文件{0}出现问题", folder)); } tcpComm.addSendBle(returnMsg); user.UpdateDownLand(sendFileFullPath); }
/// <summary> /// 消息接收事件处理程序 /// </summary> /// <param name="tcpComm"></param> /// <param name="ble"></param> void newBlemessageEventFun(tcpDataCommunication tcpComm, BLE.BLEData ble) { string s1 = ble.ToString(); stringMsg m2 = stringMsg.jsonToModel(s1); newMessageEvent?.Invoke(tcpComm, m2); }
//新消息事件 void newBlemessageEventFun(tcpDataCommunication tcpComm, BLEData ble) { //string jsonText = ((BLE.bleClass.t11)ble).msg; //JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); stringMsg msg = stringMsg.jsonToModel(ble.ToString()); switch (msg.name) { case msgEnum.dengru: //bool bl = Convert.ToBoolean(jo["value"]["return"]); bool bl = Convert.ToBoolean(msg.value["return"]); if (bl) { RetUser curr = JsonConvert.DeserializeObject <RetUser>(msg.value["jsonCurr"]); ConfigInfo ConfigInfo1 = JsonConvert.DeserializeObject <ConfigInfo>(msg.value["ConfigInfo"]); //RetUser curr = user.Login(login.textBox1.Text, login.textBox2.Text); CurrUser.currUser = curr.User; CurrUser.config = ConfigInfo1; CloseFrom2(); ShowFile(curr.User.ID); } else { // zTcpClient1.tcpComm.stop(); MessageBox.Show("账号或密码错误!"); } break; case msgEnum.liaotian: //string groupSendingMsg = jo["value"]["groupSending"].ToString(); string reciveMsg = ""; if (msg.value.Keys.Contains("groupSending")) { reciveMsg = msg.value["groupSending"]; } else if (msg.value.Keys.Contains("singleSending")) { reciveMsg = msg.value["singleSending"]; } showMsg(reciveMsg); break; case msgEnum.returnUserFileList: ResetList(msg); break; case msgEnum.fileUpload: fileUpload(tcpComm, ble); break; default: break; } }
//登陆 private void button1_Click(object sender, EventArgs e) { string account = textBox1.Text; string password = textBox2.Text; stringMsg sm = new stringMsg(); sm.name = msgEnum.dengru; sm.value.Add("account", account); sm.value.Add("pwd", password); //Form1.tcpClient1.tcpComm.sendData(sm); tcpClient.tcpComm.sendData(sm); //Form1.tcpClient1.tcpComm.newBleMessageEvent += newBlemessageEventFun; }
void denglu(tcpDataCommunication tcpComm, stringMsg msg) { string account = msg.value["account"]; string pwd = msg.value["pwd"]; bool bl = user.Login(account, pwd); BLE.stringMsg m1 = new BLE.stringMsg(); m1.name = BLE.msgEnum.dengru; m1.value.Add("return", bl.ToString()); tcpComm.sendData(m1); }
void getUserFileList(tcpDataCommunication tcpComm, stringMsg msg) { if (tcpComm.user == null) { return; } List <DB.FileInfo> list = user.GetFileListByUserId(tcpComm.user.ID); stringMsg ret = new stringMsg(); ret.name = msgEnum.returnUserFileList; ret.value["value"] = JsonConvert.SerializeObject(list); tcpComm.addSendBle(ret); }
/// <summary> /// 消息接收事件处理程序 /// </summary> /// <param name="tcpComm"></param> /// <param name="ble"></param> void newBlemessageEventFun(tcpDataCommunication tcpComm, BLE.BLEData ble) { string s1 = ""; if (ble.command == BLEcommand.t11) { s1 = ble.ToString(); } else if (ble.command == BLEcommand.t12) { s1 = ((BLE.bleClass.t12)ble).ReceiveFullMsg; } stringMsg m2 = stringMsg.jsonToModel(s1); newMessageEvent?.Invoke(tcpComm, m2); }
void fileUpload(tcpDataCommunication tcpComm, BLEData msg) { stringMsg m1 = stringMsg.jsonToModel(msg.ToString()); if (m1.value["saveFileFullPath"].Trim() == "") { showMsg("<下载失败,服务端文件不存在>"); // MessageBox.Show("下载失败,服务端文件不存在", "提示"); return; } string fileName = System.IO.Path.GetFileName(m1.value["saveFileFullPath"]); showMsg(string.Format("<{0} 下载完成>", fileName)); //MessageBox.Show("下载完成", "提示"); }
//显示文件列表 private void ResetList(stringMsg msg) { if (this.InvokeRequired) { this.BeginInvoke(new Action <stringMsg>(ResetList), msg); return; } List <DB.FileInfo> list = JsonConvert.DeserializeObject <List <DB.FileInfo> >(msg.value["value"]); this.listView1.Items.Clear(); foreach (DB.FileInfo item in list) { //ListViewItem lvi = new ListViewItem(); //lvi.Text = item.FileName; //lvi.Name = item.FilePath; listView1.Items.Add(createFileItem(item)); } }
private bool AddFileInfo(stringMsg msg) { int userId = Convert.ToInt32(msg.value["UserId"]); string filePath = msg.value["saveFileFullPath"]; string firstFloor = msg.value["FirstFloor"]; string fileName = msg.value["FileName"]; bool bl = user.AddFileInfo(userId, filePath, firstFloor, fileName); if (bl) { user.Add_Log_Opera(userId, "", string.Format("上传文件{0}", fileName)); } else { user.Add_Log_Error(userId, "", string.Format("上传文件{0}出现问题", fileName)); } return(bl); }
/// <summary> /// 消息接收事件处理程序 /// </summary> /// <param name="tcpComm"></param> /// <param name="msg"></param> void newBlemessageEventFun(tcpDataCommunication tcpComm, stringMsg msg) { switch (msg.name) { case msgEnum.liaotian: liaotian(tcpComm, msg); break; case msgEnum.fileUpload: showMsg(string.Format("收到文件", msg.value["value"])); break; case msgEnum.dengru: denglu(tcpComm, msg); break; default: break; } }
void denglu(tcpDataCommunication tcpComm, stringMsg msg) { string address = tcpComm.tcpClientId.Split('&')[2]; string account = msg.value["account"]; string pwd = msg.value["pwd"]; RetUser curr = user.Login(account, pwd); BLE.stringMsg m1 = new BLE.stringMsg(); m1.name = BLE.msgEnum.dengru; m1.value.Add("return", curr.Success.ToString()); if (curr.Success) { tcpComm.user = curr.User; if (Common.UserViewList == null) { Common.UserViewList = new List <UserView>(); } Common.UserViewList.Add(new UserView() { ID = curr.User.ID, Name = curr.User.Account, Address = address }); BindDataGridView(Common.UserViewList); m1.value.Add("ID", curr.User.ID.ToString()); string jsonCurr = JsonConvert.SerializeObject(curr); m1.value.Add("jsonCurr", jsonCurr); ConfigInfo config = user.GetSave(); string jsonConfig = JsonConvert.SerializeObject(config); m1.value.Add("ConfigInfo", jsonConfig); } tcpComm.sendData(m1); // UserService user = new UserService(); }
private void button7_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { BLE.bleClass.t12 t2 = new BLE.bleClass.t12(); t2.sendFileFullPath = openFileDialog1.FileName; string fileName = System.IO.Path.GetFileName(t2.sendFileFullPath); string reviced = System.IO.Path.Combine("d:\\", fileName); stringMsg sm = new stringMsg(); sm.name = msgEnum.fileUpload; sm.value.Add("value", reviced); t2.ReceiveFullMsg = sm.modelToJson(); t2.toBleStream(tcpClient1.tcpComm.sendDataGetStream()); //tcpClient1.tcpComm.sendData(t2.toBleStream()); } }
//下载方法 private void DownLand2() { if (this.listView1.SelectedItems.Count > 0) { string folder = this.listView1.SelectedItems[0].SubItems[0].Text.ToString().Trim(); string sendFileFullPath = this.listView1.SelectedItems[0].Tag == null ? "" : this.listView1.SelectedItems[0].Tag.ToString(); if (sendFileFullPath.Length > 0) { //选中文件 下载 string msg = "确定要下载 " + folder + " 吗?"; //if ((int)MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == 1) { this.saveFileDialog2.FileName = System.IO.Path.GetFileName(sendFileFullPath); if (this.saveFileDialog2.ShowDialog() == DialogResult.OK) { try { //下载 string saveFileFullPath = saveFileDialog2.FileName; stringMsg m1 = new stringMsg(); m1.name = msgEnum.getDownLandFile; m1.value.Add("sendFileFullPath", sendFileFullPath); m1.value.Add("saveFileFullPath", saveFileFullPath); this.zTcpClient1.tcpComm.addSendBle(m1); } catch (Exception ex) { tools.log.writeLog("DownloadDataException:{0},文件信息:{1}", ex.Message, sendFileFullPath); } } } } } }
/// <summary> /// 返回1代表继续接收,返回0代表接收结束 /// </summary> /// <param name="b"></param> /// <returns></returns> public override int writeByte(byte b) { ////写入返回值 int writeRet = -1; currentPosition++; switch (currentPosition) { case 0: case 1: case 2: case 3: /////标识消息总长度8位 case 4: case 5: case 6: case 7: case 8: case 9: headByte.Add(b); break; case 10: headByte.Add(b); try { allDataLength = BLEData.byteToInt64(headByte[3], headByte[4], headByte[5], headByte[6], headByte[7], headByte[8], headByte[9], headByte[10]); } catch { errorData(); return(0); } // dataLength = BLE.BLEData.getInt16(data[2], data[3]); break; case 11: ////这4位代表消息内容的长度 case 12: case 13: msgByteLengthByte.Add(b); break; case 14: msgByteLengthByte.Add(b); msgByteLength = byteToInt32(msgByteLengthByte.ToArray()); break; case 15: ////这8位代表文件的长度 case 16: case 17: case 18: case 19: case 20: case 21: fileDataLengthByte.Add(b); break; case 22: fileDataLengthByte.Add(b); fileDataLength = byteToInt64(fileDataLengthByte.ToArray()); break; default: int beforIndex = 22; if (currentPosition < beforIndex + msgByteLength) { ////当前位置小于消息长度,为消息内容 msgByte.Add(b); } else if (currentPosition == beforIndex + msgByteLength) { ////当前位置等于消息长度,为消息结尾 msgByte.Add(b); string msgJson = getString(msgByte.ToArray()); // stringMsg sm = stringMsg.jsonToModel(pathJson); this.ReceiveFullMsg = msgJson; try { stringMsg FullMsg = stringMsg.jsonToModel(msgJson); string rfmPath = FullMsg.value["saveFileFullPath"]; if (rfmPath.Trim() == "") { errorData(); return(0); } string dir = System.IO.Path.GetDirectoryName(rfmPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } fileWrite = System.IO.File.Create(rfmPath); //ReceiveFullMsg } #region 创建文件异常处理 catch (UnauthorizedAccessException ex1) { errorData(); return(0); } catch (ArgumentException ex1) { errorData(); return(0); } catch (PathTooLongException ex1) { errorData(); return(0); } catch (DirectoryNotFoundException ex1) { errorData(); return(0); } catch (IOException ex1) { errorData(); return(0); } catch (NotSupportedException ex1) { errorData(); return(0); } #endregion } else if (currentPosition < beforIndex + msgByteLength + fileDataLength) { ////当前位置小于文件长度,为文件内容 fileWrite.WriteByte(b); fileWrite.Flush(); } else if (currentPosition >= beforIndex + msgByteLength + fileDataLength) { ////消息结束 fileWrite.WriteByte(b); fileWrite.Flush(); fileWrite.Close(); successData(); return(0); } break; } return(1); }
public override void toBleStream(System.IO.Stream sr) { //try //{ stringMsg Msg = stringMsg.jsonToModel(ReceiveFullMsg); string sendFileFullPath = Msg.value["sendFileFullPath"]; byte[] FullMsg = getByte(ReceiveFullMsg); byte[] FullMsgLength = getByte(FullMsg.Length); Stream fileStream = System.IO.File.OpenRead(sendFileFullPath); byte[] streamLength = getByte(fileStream.Length); ////////////////////// //////////////// allDataLength = FullMsgLength.LongLength + FullMsg.LongLength; ///1 messageData[0] = FullMsgLength; //2 messageData[1] = streamLength; ///3 messageData[2] = FullMsg; ///3 List <byte> l1 = new List <byte>(); l1.AddRange(head); l1.Add((byte)command); l1.AddRange(getByte(this.allDataLength)); sr.Write(l1.ToArray(), 0, l1.Count); sr.Write(messageData[0], 0, messageData[0].Count());///报连接错误 sr.Write(messageData[1], 0, messageData[1].Count()); sr.Write(messageData[2], 0, messageData[2].Count()); fileStream.CopyTo(sr); #region 手动流复制 ////手动流复制 //byte[] bytes = new byte[128]; //float num = 0; //while (true) //{ // // byte[] srByte = StreamToBytes(sr, num); // int n = fileStream.Read(bytes, 0, 128); // if (n == 0) // { // break; // } // sr.Write(bytes, 0, n); // num += n; // currProgress = int.Parse(Math.Ceiling((num / fileStream.Length)*100).ToString()); //} ///// #endregion fileStream.Close(); //} //catch (Exception ex) //{ // string x = string.Format(@"[Message]:{0},[StackTrace]:{1},[Source]:{2},[TargetSite]:{3},[HResult]:{4}", ex.Message, ex.StackTrace, ex.Source, ex.TargetSite, ex.HResult); // string y = x; //} }
//给服务端发送文件 private void button7_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { //BLE.bleClass.t12 t2 = new BLE.bleClass.t12(); string sendFileFullPath = openFileDialog1.FileName; string fileName = System.IO.Path.GetFileName(sendFileFullPath); //// ConfigInfo config = user.GetSave(); string saveFileFullPath = System.IO.Path.Combine(CurrUser.config.Path + "\\" + CurrUser.currUser.ID, fileName);//d:\\ stringMsg sm = new stringMsg(); sm.name = msgEnum.fileUpload; sm.value.Add("saveFileFullPath", saveFileFullPath); //全路径 sm.value.Add("sendFileFullPath", sendFileFullPath); //全路径 //sm.value.Add("value", saveFileFullPath);//全路径 sm.value.Add("UserId", CurrUser.currUser.ID.ToString()); //用户id sm.value.Add("FirstFloor", CurrUser.currUser.ID.ToString()); //用户专属文件夹 sm.value.Add("FileName", fileName); //文件名称 //sm.value.Add("fileDirFullPath", CurrUser.config.Path + "\\" + CurrUser.currUser.ID);//文件存储路径 //t2.ReceiveFullMsg = sm.modelToJson(); //改为队列 //t2.toBleStream(zTcpClient1.tcpComm.sendDataGetStream()); zTcpClient1.tcpComm.addSendBle(sm); // BLE.BLEData currentSend = zTcpClient1.tcpComm.currentSendBleData; //发送文件队列 目前问题没有第一个发送的currentSendBleData // waitSendBleData = zTcpClient1.tcpComm.waitSendList; //this.listView2.Columns.Clear(); //this.listView2.Columns.Add("文件名", 500, HorizontalAlignment.Left); //this.listView2.Columns.Add("进度", 100, HorizontalAlignment.Left); //currentSend.currProgress //传输的文件 //if (currentSend != null) //{ //System.Timers.Timer t = new System.Timers.Timer(500);//实例化Timer类,设置间隔时间为10000毫秒; //t.Elapsed += new System.Timers.ElapsedEventHandler(currProgress, currentSend,); //t.AutoReset = true; // NewMethod(currentSend); //} // timer = new System.Threading.Timer(currProgress, currentSend, TimeSpan.FromSeconds(0), TimeSpan.FromMilliseconds(200)); //队列中尚未传输 //for (int i = 0; i < currentSendBleData.Count; i++) //{ // BLE.bleClass.t12 t12_wait = (BLE.bleClass.t12)currentSendBleData[i]; // stringMsg msg_wait = stringMsg.jsonToModel(t12_wait.ToString()); // string fName_wait = msg_wait.value["FileName"]; // ListViewItem lvi_wait = new ListViewItem(); // lvi_wait.Text = fName_wait; // lvi_wait.SubItems.Add("等待中..."); // this.listView2.Items.Add(lvi_wait); //} } }
void denglu(tcpDataCommunication tcpComm, stringMsg msg) { string value = msg.value["return"]; MessageBox.Show(value); }
void newMessageEventFun(tcpDataCommunication comm, stringMsg msg) { }
void liaotian(tcpDataCommunication tcpComm, stringMsg msg) { showMsg(tcpComm.tcpClient1.Client.RemoteEndPoint.ToString() + "---" + msg.value["value"]); }