private void User_DataAv(newCLient sender, HeaderDsc header, byte[] data) //обработка данных { Task t = new Task(() => DataProc(sender, header, data)); t.Start(); //DataProc(sender, header, data); }
private void deSerializeList(byte[] data, HeaderDsc headerDsc) { using (MemoryStream Memory = new MemoryStream(headerDsc.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); newClientList = (List <ClSpec>)bf.Deserialize(Memory); } }
private void clientSendCommand(newCLient sender, HeaderDsc header, byte[] data) { if (sender.clientState == 1) // если сообщение получено от серверного приложения { try { Cmd cmd = new Cmd(); using (MemoryStream Memory = new MemoryStream(header.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); cmd = (Cmd)bf.Deserialize(Memory); } foreach (Guid guid in cmd.list) // поиск выбранных клиентов { foreach (newCLient cl in ClientList) { if (cl.clSpec.settings == null) { break; } if (cl.clSpec.settings.guid == guid) { byte[] index = BitConverter.GetBytes(header.comIndex); cl.Send(ServiceMessage.clCommand, this.guid, index); } } } } catch (Exception ex)// отправка ошибки на серверное приложение { string erMsg = ex.ToString() + " SERVER EXCEPTION WHILE SENDING CLIENT COMMAND"; sender.Send(ServiceMessage.error, guid, Encoding.Default.GetBytes(erMsg)); } } else // если это ответ от клиента { foreach (newCLient client in ClientList) { if (client.clientState == 1) { client.Send(ServiceMessage.clCommand, guid, data); } } } }
private void DataProcess(byte[] data, HeaderDsc headerDsc) { switch (headerDsc.Message) { case ServiceMessage.file: break; case ServiceMessage.data: break; case ServiceMessage.clCommand: int comIndex = 0; BitConverter.ToInt32(data, comIndex); string s = clCommand(comIndex); byte[] answer1 = Encoding.Default.GetBytes(s); this.Send(ServiceMessage.clCommand, settings.guid, answer1); break; case ServiceMessage.cmd: string str = Encoding.Default.GetString(data); Cmd ans = new Cmd(); ans.strCmd = runCommand(str); ans.destGuid = settings.guid; byte[] answer; using (MemoryStream Memory = new MemoryStream()) // сериализация заголовка { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(Memory, ans); Memory.Position = 0; answer = new byte[Memory.Length]; var r = Memory.Read(answer, 0, answer.Length); } this.Send(ServiceMessage.cmd, settings.guid, answer); break; } }
public void SendFile(ServiceMessage message, Guid guid, string path, string ext) { byte[] buffer; byte[] header; byte[] infobuffer; //??? NetworkStream Network; HeaderDsc headerDsc; if (tcpClient == null || !tcpClient.Connected) { ErrorMsg = "Удаленный хост принудительно разорвал существующее подключение."; return; } try { byte[] data = file.GetBytes(path); headerDsc = new HeaderDsc(); // формирование заголовка headerDsc.Message = message; headerDsc.guid = guid; headerDsc.ext = ext; headerDsc.Hex = file.CheckSum(path); // хэш сумма для проверки целостности headerDsc.DataSize = data.Length; using (MemoryStream Memory = new MemoryStream()) // сериализация заголовка { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(Memory, headerDsc); Memory.Position = 0; infobuffer = new byte[Memory.Length]; var r = Memory.Read(infobuffer, 0, infobuffer.Length); } buffer = new byte[TCPPack.BufferSize]; header = BitConverter.GetBytes(infobuffer.Length); Buffer.BlockCopy(header, 0, buffer, 0, header.Length); Buffer.BlockCopy(infobuffer, 0, buffer, header.Length, infobuffer.Length); int bufferShift = header.Length + infobuffer.Length; // сдвиг на размер заголовка int rdShift = 0; // сдвиг на кол-во переданных байт int lengthPack = 0; // фактический размер буффера Network = tcpClient.GetStream(); while (rdShift < (headerDsc.DataSize + bufferShift)) // пока переданное кол-во байтов меньше ожидаемого { var remBytes = headerDsc.DataSize - rdShift; if (remBytes < buffer.Length) { lengthPack = remBytes; } else { lengthPack = buffer.Length - bufferShift; } Buffer.BlockCopy(data, rdShift, buffer, bufferShift, lengthPack); rdShift += lengthPack; Network.Write(buffer, 0, lengthPack + bufferShift); bufferShift = 0; } } catch (Exception ex) { ErrorMsg = ex.Message; this.Disonnect(); } finally { header = null; infobuffer = null; buffer = null; Network = null; headerDsc = null; } }
private void DataProc(newCLient sender, HeaderDsc header, byte[] data) { switch (header.Message) { case ServiceMessage.file: // получение файла FilePr file = new FilePr(); string path = "123" + header.ext; File.WriteAllBytes(path, data); if (!(file.CheckSum(path) == header.Hex)) { Console.WriteLine("file damaged"); // проверка целостности файла } break; case ServiceMessage.data: break; case ServiceMessage.Authorization: // подключение newUserAv(sender); Console.WriteLine("Authorization message from "); Console.WriteLine(sender.settings.guid); break; case ServiceMessage.Server: // подключение серверного приложения sender.clientState = 1; Console.WriteLine("///server app connected\n"); List <ClSpec> listCl = new List <ClSpec>(); // формирование перечисления описаний клиентов foreach (newCLient cl in ClientList) { if (cl.clSpec.settings == null) { cl.clSpec.settings = new xmlSettings.XmlSet(); } listCl.Add(cl.clSpec); } byte[] clList; using (MemoryStream Memory = new MemoryStream()) // сериализация перечисления { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(Memory, listCl); Memory.Position = 0; clList = new byte[Memory.Length]; var r = Memory.Read(clList, 0, clList.Length); } sender.SendCl(ServiceMessage.clList, this.guid, clList, 0); break; case ServiceMessage.cmd: // комманда коммандной строки if (sender.clientState == 1) // если сообщение получено от серверного приложения { Console.WriteLine("cmd get from serv app\n"); try { Cmd cmd = new Cmd(); using (MemoryStream Memory = new MemoryStream(header.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); cmd = (Cmd)bf.Deserialize(Memory); } foreach (Guid guid in cmd.list) // поиск выбранных клиентов { foreach (newCLient cl in ClientList) { if (cl.clSpec.settings == null) { ; } else { if (cl.clSpec.settings.guid == guid) { byte[] str = Encoding.Default.GetBytes(cmd.strCmd); cl.Send(ServiceMessage.cmd, this.guid, str); } } } } } catch (Exception ex) // отправка ошибки на серверное приложение { string erMsg = ex.ToString() + " SERVER EXCEPTION WHILE SENDING CMD"; sender.Send(ServiceMessage.error, guid, Encoding.Default.GetBytes(erMsg)); } } else // если это ответ от клиента { Console.WriteLine("cmd response get from" + sender.tcpClient.ToString()); foreach (newCLient client in ClientList) { if (client.clientState == 1) { client.Send(ServiceMessage.cmd, guid, data); } } } break; case ServiceMessage.servCommand: break; case ServiceMessage.clCommand: clientSendCommand(sender, header, data); break; } }
private void DataProcess(byte[] data, HeaderDsc headerDsc) { switch (headerDsc.Message) { case ServiceMessage.file: break; case ServiceMessage.data: break; case ServiceMessage.clList: switch (headerDsc.comIndex) { case 0: deSerializeList(data, headerDsc); if (ClientList.Count == 0) { foreach (ClSpec c2 in newClientList) { ClientList.Add(c2); newClientConnected(c2.settings.guid, c2.ipAdr); } } else { foreach (ClSpec c in newClientList) { bool isNew = false; foreach (ClSpec c1 in ClientList) { if (c1.settings == null) { c1.settings = new XmlSet(); } if (c.settings.guid == c1.settings.guid) { newClientConnected(c.settings.guid, c.ipAdr); isNew = false; break; } else { isNew = true; } } if (isNew) { newClientConnected(c.settings.guid, c.ipAdr); ClientList.Add(c); } } } break; case 1: ClSpec cl = new ClSpec(); using (MemoryStream Memory = new MemoryStream(headerDsc.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); cl = (ClSpec)bf.Deserialize(Memory); } newClientConnected(cl.settings.guid, cl.ipAdr); bool isNew1 = false; foreach (ClSpec c in ClientList) { if (c.settings.guid != cl.settings.guid) { isNew1 = true; } } if (isNew1) { ClientList.Add(cl); } break; case 2: ClSpec cl1 = new ClSpec(); using (MemoryStream Memory = new MemoryStream(headerDsc.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); cl1 = (ClSpec)bf.Deserialize(Memory); } ClientDisconneted(cl1.settings.guid, cl1.ipAdr); break; } break; case ServiceMessage.cmd: Form2 formAnsw = new Form2(); Cmd cmd = new Cmd(); using (MemoryStream Memory = new MemoryStream(headerDsc.DataSize)) // десериализация заголовка { Memory.Write(data, 0, data.Length); Memory.Position = 0; BinaryFormatter bf = new BinaryFormatter(); cmd = (Cmd)bf.Deserialize(Memory); } GetCmdResponse(cmd); break; case ServiceMessage.clCommand: MessageBox.Show(Encoding.Default.GetString(data)); break; case ServiceMessage.servCommand: MessageBox.Show(Encoding.Default.GetString(data)); break; case ServiceMessage.error: MessageBox.Show(Encoding.Default.GetString(data)); break; } }