Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.48 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.IO;
  11. using System.Net.Sockets;
  12. using System.Net;
  13. using System.Threading;
  14. //using System.Data.SqlClient;
  15. using System.Net.NetworkInformation;
  16. using System.Runtime.InteropServices;
  17. using System.Windows;
  18.  
  19. namespace Peredacha
  20. {
  21. public partial class Form1 : Form
  22. {
  23. String IP;
  24. int combo;
  25. public Form1()
  26. {
  27. InitializeComponent();
  28. //Создаем поток для приема сообщений
  29. new Thread(new ThreadStart(Receiver)).Start();
  30. new Thread(new ThreadStart(FileReceiver)).Start();
  31. }
  32. //Метод потока
  33. protected void Receiver()
  34. {
  35. //Создаем Listener на порт "по умолчанию"
  36. TcpListener Listen = new TcpListener(7000);
  37. //Начинаем прослушку
  38. Listen.Start();
  39. //и заведем заранее сокет
  40. Socket ReceiveSocket;
  41. while (true)
  42. {
  43. try
  44. {
  45. //Пришло сообщение
  46. ReceiveSocket = Listen.AcceptSocket();
  47. Byte[] Receive = new Byte[256];
  48. //Читать сообщение будем в поток
  49. using (MemoryStream MessageR = new MemoryStream())
  50. {
  51. //Количество считанных байт
  52. Int32 ReceivedBytes;
  53. do
  54. {//Собственно читаем
  55. ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
  56. //и записываем в поток
  57. MessageR.Write(Receive, 0, ReceivedBytes);
  58. //Читаем до тех пор, пока в очереди не останется данных
  59. } while (ReceiveSocket.Available > 0);
  60. //Добавляем изменения в ChatBox
  61. ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Получаю: " + Encoding.Default.GetString(MessageR.ToArray()), ChatBox });
  62.  
  63. }
  64. }
  65. catch (System.Exception ex)
  66. {
  67. MessageBox.Show(ex.Message);
  68. }
  69.  
  70. }
  71. }
  72.  
  73. //Метод потока
  74. protected void FileReceiver()
  75. {
  76. //Создаем Listener на порт "по умолчанию"
  77. TcpListener Listen = new TcpListener(6999);
  78. //Начинаем прослушку
  79. Listen.Start();
  80. //и заведем заранее сокет
  81. Socket ReceiveSocket;
  82. while (true)
  83. {
  84. try
  85. {
  86. string name;
  87. //Пришло сообщение
  88. ReceiveSocket = Listen.AcceptSocket();
  89. Byte[] Receive = new Byte[256];
  90. //Читать сообщение будем в поток
  91. using (MemoryStream MessageR = new MemoryStream())
  92. {
  93.  
  94. //Количество считанных байт
  95. Int32 ReceivedBytes;
  96. Int32 Firest256Bytes = 0;
  97. String FilePath = "";
  98. do
  99. {//Собственно читаем
  100. ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
  101. //Разбираем первые 256 байт
  102. if (Firest256Bytes < 256)
  103. {
  104. Firest256Bytes += ReceivedBytes;
  105. Byte[] ToStr = Receive;
  106. //Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
  107. if (Firest256Bytes > 256)
  108. {
  109. Int32 Start = Firest256Bytes - ReceivedBytes;
  110. Int32 CountToGet = 256 - Start;
  111. Firest256Bytes = 256;
  112. //В случае если было принято >256 байт (двумя сообщениями к примеру)
  113. //Остаток (до 256) записываем в "путь файла"
  114. ToStr = Receive.Take(CountToGet).ToArray();
  115. //А остальную часть - в будующий файл
  116. Receive = Receive.Skip(CountToGet).ToArray();
  117. MessageR.Write(Receive, 0, ReceivedBytes);
  118. }
  119. //Накапливаем имя файла
  120. FilePath += Encoding.Default.GetString(ToStr);
  121. }
  122. else
  123.  
  124. //и записываем в поток
  125. MessageR.Write(Receive, 0, ReceivedBytes);
  126. //Читаем до тех пор, пока в очереди не останется данных
  127. } while (ReceivedBytes == Receive.Length);
  128. //Убираем лишние байты
  129. String resFilePath = FilePath.Substring(0, FilePath.IndexOf(''));
  130. using (var File = new FileStream(resFilePath, FileMode.Create))
  131. {//Записываем в файл
  132. File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);
  133. }//Уведомим пользователя
  134. ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Получено: " + resFilePath, ChatBox });
  135. name = resFilePath;
  136. }
  137. /* DataRow workRow = bD1DataSet.Tables[0].NewRow();//BD1DataSet1.Tables[0].NewRow();
  138. workRow["id"] = 1;
  139. workRow["data"] = System.DateTime.Now.ToLongDateString();
  140. workRow["time"] = System.DateTime.Now.ToLongTimeString();
  141. workRow["nazv"] = name;
  142. bD1DataSet.Tables[0].Rows.Add(workRow);
  143. this.Validate();
  144. this.ipadressBindingSource.EndEdit();
  145. this.tableAdapterManager1.UpdateAll(this.bD1DataSet);*/
  146. }
  147. catch (System.Exception ex)
  148. {
  149. MessageBox.Show(ex.Message);
  150. }
  151.  
  152. }
  153. }
  154.  
  155. /// <summary>
  156. /// Отправляет сообщение в потоке на IP, заданный в контроле IP
  157. /// </summary>
  158. /// <param name="Message">Передаваемое сообщение</param>
  159. void ThreadSend(object Message)
  160. {
  161. try
  162. {
  163. //Проверяем входной объект на соответствие строке
  164. String MessageText = "";
  165. if (Message is String)
  166. {
  167. MessageText = Message as String;
  168. }
  169. else
  170. throw new Exception("На вход необходимо подавать строку");
  171.  
  172. Byte[] SendBytes = Encoding.Default.GetBytes(MessageText);
  173. //Создаем сокет, коннектимся
  174. IPEndPoint EndPoint = new IPEndPoint(IPAddress.Parse(IP), 7000);
  175. Socket Connector = new Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  176. Connector.Connect(EndPoint);
  177. Connector.Send(SendBytes);
  178. Connector.Close();
  179. //Изменяем поле сообщений (уведомляем, что отправили сообщение)
  180.  
  181. ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Отправлено " + MessageText, ChatBox });
  182. }
  183. catch (Exception ex)
  184. {
  185. MessageBox.Show(ex.Message);
  186. }
  187.  
  188. }
  189.  
  190. //Делегат доступа к контролам формы
  191. delegate void SendMsg(String Text, RichTextBox Rtb);
  192.  
  193. SendMsg AcceptDelegate = (String Text, RichTextBox Rtb) =>
  194. {
  195. Rtb.Text += Text + "n";
  196. };
  197.  
  198. private void button1_Click(object sender, EventArgs e)
  199. {
  200. IP = comboBox1.Text;
  201. Ping ping = new Ping();
  202. PingReply reply = ping.Send(IP);
  203. if (reply.Status != IPStatus.Success)
  204. {
  205. MessageBox.Show("Не удаётся подключиться!");
  206. button2.Enabled = false;
  207. }
  208. else {
  209. button2.Enabled = true;
  210. //Отправляем файл
  211. //Добавим на форму OpenFileDialog и вызовем его
  212. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  213. {
  214. //Коннектимся
  215. IPEndPoint EndPoint = new IPEndPoint(IPAddress.Parse(IP), 6999);
  216. Socket Connector = new Socket(EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  217. Connector.Connect(EndPoint);
  218. //Получаем имя из полного пути к файлу
  219. StringBuilder FileName = new StringBuilder(openFileDialog1.FileName);
  220. //Выделяем имя файла
  221. int index = FileName.Length - 1;
  222. while (FileName[index] != '\' && FileName[index] != '/')
  223. {
  224. index--;
  225. }
  226. //Получаем имя файла
  227. String resFileName = "";
  228. for (int i = index + 1; i < FileName.Length; i++)
  229. resFileName += FileName[i];
  230. //Записываем в лист
  231. List<Byte> First256Bytes = Encoding.Default.GetBytes(resFileName).ToList();
  232. Int32 Diff = 256 - First256Bytes.Count;
  233. //Остаток заполняем нулями
  234. for (int i = 0; i < Diff; i++)
  235. First256Bytes.Add(0);
  236. //Начинаем отправку данных
  237. System.IO.FileInfo file = new System.IO.FileInfo(openFileDialog1.FileName);
  238. long size = file.Length;
  239. Byte[] ReadedBytes = new Byte[256];
  240. using (var FileStream = new FileStream(openFileDialog1.FileName, FileMode.Open))
  241. {
  242. using (var Reader = new BinaryReader(FileStream))
  243. {
  244. Int32 CurrentReadedBytesCount;
  245. //Вначале отправим название файла
  246. Connector.Send(First256Bytes.ToArray());
  247. do
  248. {
  249. //Затем по частям - файл
  250. CurrentReadedBytesCount = Reader.Read(ReadedBytes, 0, ReadedBytes.Length);
  251. Connector.Send(ReadedBytes, CurrentReadedBytesCount, SocketFlags.None);
  252. }
  253. while (CurrentReadedBytesCount == ReadedBytes.Length);
  254. }
  255. }
  256. //Завершаем передачу данных
  257. Connector.Close();
  258.  
  259. }
  260.  
  261.  
  262.  
  263. }
  264. }
  265.  
  266. private void button2_Click(object sender, EventArgs e)
  267. {
  268. // переместить на клавишу отправки связать с progressBar
  269. // System.IO.FileInfo file = new System.IO.FileInfo(openFileDialog1.FileName);
  270. // long size = file.Length;
  271. // MessageBox.Show(size.ToString()); // для проверки вывода размера файла
  272. new Thread(new ParameterizedThreadStart(ThreadSend)).Start("Получение"); //otpravka
  273. }
  274.  
  275. private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  276. {
  277. Environment.Exit(0);
  278. }
  279.  
  280. private void Form1_Load(object sender, EventArgs e)
  281. {
  282. // TODO: данная строка кода позволяет загрузить данные в таблицу "bD1DataSet.dannie". При необходимости она может быть перемещена или удалена.
  283. this.dannieTableAdapter.Fill(this.bD1DataSet.dannie);
  284. // TODO: данная строка кода позволяет загрузить данные в таблицу "bD1DataSet.ip_adress". При необходимости она может быть перемещена или удалена.
  285. this.ip_adressTableAdapter.Fill(this.bD1DataSet.ip_adress);
  286.  
  287. }
  288.  
  289. private void button3_Click(object sender, EventArgs e)
  290. {
  291. panel2.Visible = false;
  292. }
  293.  
  294. private void button4_Click(object sender, EventArgs e)
  295. {
  296. String stro;
  297. combo = comboBox1.Items.Count;
  298. combo = combo + 1;
  299. stro = IP1.Text + "." + IP2.Text + "." + IP3.Text + "." + IP4.Text;
  300. bD1DataSet.Tables[1].Rows.Add(combo, textBox1.Text, stro);
  301. this.Validate();
  302. this.ipadressBindingSource.EndEdit();
  303. this.tableAdapterManager1.UpdateAll(this.bD1DataSet);
  304. panel2.Visible = false;
  305. panel1.Visible = true;
  306. }
  307.  
  308. private void добавитьКомпьютерToolStripMenuItem_Click(object sender, EventArgs e)
  309. {
  310. panel1.Visible = false;
  311. panel2.Visible = true;
  312. panel3.Visible = false;
  313. }
  314.  
  315. private void посмотретьВсеКомпьютерыToolStripMenuItem_Click(object sender, EventArgs e)
  316. {
  317. // Form2 f = new Form2();
  318. //f.Show();
  319. panel3.Visible = true;
  320. panel1.Visible = false;
  321. panel2.Visible = false;
  322. dannieDataGridView.Visible = false;
  323. ip_adressDataGridView.Visible = true;
  324. bindingNavigator1.Visible = true;
  325. bindingNavigator2.Visible = false;
  326. }
  327.  
  328. private void button3_Click_1(object sender, EventArgs e)
  329. {
  330. panel2.Visible = false;
  331. IP1.Text = ""; IP2.Text = ""; IP3.Text = ""; IP4.Text = "";
  332. textBox1.Text = "";
  333. }
  334.  
  335. private void IP1_TextChanged(object sender, EventArgs e)
  336. {
  337. String a;
  338. int f;
  339. a = IP1.Text;
  340. try
  341. {
  342. f = int.Parse(a);
  343. for (int i = 0; i <= 10; i++)
  344. {
  345. if (f == i) { a = i.ToString(); }
  346. }
  347. }
  348. catch
  349. {
  350. if (IP1.Text != "") { MessageBox.Show("Не верный символ!"); IP1.Text = ""; }
  351. }
  352. }
  353.  
  354. private void IP2_TextChanged(object sender, EventArgs e)
  355. {
  356. String a;
  357. int f;
  358. a = IP2.Text;
  359. try
  360. {
  361. f = int.Parse(a);
  362. for (int i = 0; i <= 10; i++)
  363. {
  364. if (f == i) { a = i.ToString(); }
  365. }
  366. }
  367. catch
  368. {
  369. if (IP2.Text != "") { MessageBox.Show("Не верный символ!"); IP2.Text = ""; }
  370. }
  371. }
  372.  
  373. private void IP3_TextChanged(object sender, EventArgs e)
  374. {
  375. String a;
  376. int f;
  377. a = IP3.Text;
  378. try
  379. {
  380. f = int.Parse(a);
  381. for (int i = 0; i <= 10; i++)
  382. {
  383. if (f == i) { a = i.ToString(); }
  384. }
  385. }
  386. catch
  387. {
  388. if (IP3.Text != "") { MessageBox.Show("Не верный символ!"); IP3.Text = ""; }
  389. }
  390. }
  391.  
  392. private void IP4_TextChanged(object sender, EventArgs e)
  393. {
  394. String a;
  395. int f;
  396. a = IP4.Text;
  397. try
  398. {
  399. f = int.Parse(a);
  400. for (int i = 0; i <= 10; i++)
  401. {
  402. if (f == i) { a = i.ToString(); }
  403. }
  404. }
  405. catch
  406. {
  407. if (IP4.Text != "") { MessageBox.Show("Не верный символ!"); IP4.Text = ""; }
  408. }
  409. }
  410.  
  411. private void button5_Click(object sender, EventArgs e)
  412. {
  413. }
  414.  
  415. private void button6_Click(object sender, EventArgs e)
  416. {
  417. panel3.Visible = false;
  418. panel2.Visible = false;
  419. panel1.Visible = true;
  420. }
  421.  
  422. private void посмотретьФайлыToolStripMenuItem_Click(object sender, EventArgs e)
  423. {
  424. panel3.Visible = true;
  425. panel1.Visible = false;
  426. panel2.Visible = false;
  427. dannieDataGridView.Visible = true;
  428. ip_adressDataGridView.Visible = false;
  429. bindingNavigator1.Visible = false;
  430. bindingNavigator2.Visible = true;
  431. }
  432.  
  433. private void bindingNavigator1_RefreshItems(object sender, EventArgs e)
  434. {
  435.  
  436. }
  437.  
  438. private void panel3_Paint(object sender, PaintEventArgs e)
  439. {
  440.  
  441. }
  442.  
  443. private void progressBar1_Click(object sender, EventArgs e)
  444. {
  445.  
  446. }
  447.  
  448. private void button6_Click_1(object sender, EventArgs e)
  449. {
  450. panel3.Visible = false;
  451. panel2.Visible = false;
  452. panel1.Visible = true;
  453. }
  454.  
  455. private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
  456. {
  457.  
  458. }
  459. }
  460. }
  461.  
  462. Byte[] ReadedBytes = new Byte[256];
  463.  
  464. Byte[] ReadedBytes = File.ReadAllBytes(path);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement