C# Send file over TCP


SUBMITTED BY: Guest

DATE: Dec. 7, 2013, 5:16 p.m.

FORMAT: C#

SIZE: 7.6 kB

HITS: 50345

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using System.Threading;
  9. namespace Net_Send_File
  10. {
  11. class Program
  12. {
  13. static string input;
  14. static void Main(string[] args)
  15. {
  16. while (true)
  17. {
  18. Console.Clear();
  19. Console.Title = "Main menu";
  20. Console.WriteLine("[1] Use as server");
  21. Console.WriteLine("[2] Use as client");
  22. input = Console.ReadLine();
  23. if (input.Length == 0)
  24. continue;
  25. else if (input[0] == '1')
  26. new Server();
  27. else if (input[0] == '2')
  28. new Client();
  29. else
  30. continue;
  31. }
  32. }
  33. class Server
  34. {
  35. private TcpListener listener;
  36. private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8000);
  37. private bool active;
  38. public Server()
  39. {
  40. Console.Clear();
  41. Console.Title = "Server";
  42. Main();
  43. }
  44. private void Main()
  45. {
  46. listener = new TcpListener(ipep);
  47. try
  48. {
  49. listener.Start();
  50. active = true;
  51. ListenForConnections();
  52. }
  53. catch (Exception ex)
  54. {
  55. Console.WriteLine(ex.Message);
  56. Console.ReadLine();
  57. }
  58. }
  59. private void ListenForConnections()
  60. {
  61. Console.Clear();
  62. Console.WriteLine("Listening for connections...");
  63. while (active)
  64. {
  65. TcpClient client = listener.AcceptTcpClient();
  66. Console.WriteLine("Connection @ {0}", TCPIP(client));
  67. new Thread(new ParameterizedThreadStart(HandleClientData)).Start(client);
  68. }
  69. }
  70. private void HandleClientData(object _c)
  71. {
  72. TcpClient c = (TcpClient)_c;
  73. string ipaddr = TCPIP(c);
  74. NetworkStream s = c.GetStream();
  75. byte[] buffer = new byte[1024 * 10];
  76. int bytesRead;
  77. while (active)
  78. {
  79. bytesRead = 0;
  80. try
  81. {
  82. bytesRead = s.Read(buffer, 0, buffer.Length);
  83. }
  84. catch (Exception ex)
  85. {
  86. Console.WriteLine("Socket error @ {0}:\r\n{1}", ipaddr, ex.Message);
  87. Console.ReadLine();
  88. break;
  89. }
  90. if (bytesRead == 0)
  91. {
  92. Console.WriteLine("Disconnected @ {0}", ipaddr);
  93. break;
  94. }
  95. string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
  96. using (var fs = File.OpenWrite("recieved.jpg"))
  97. {
  98. fs.Write(buffer, 0, buffer.Length);
  99. fs.Close();
  100. }
  101. }
  102. }
  103. private string TCPIP(TcpClient c)
  104. {
  105. return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
  106. }
  107. }
  108. class Client
  109. {
  110. private TcpClient client;
  111. private IPEndPoint ipep;
  112. private int port;
  113. public Client()
  114. {
  115. Console.Clear();
  116. Console.Title = "Client";
  117. bool error = false;
  118. while (true)
  119. {
  120. Console.WriteLine("IPEndPoint: ");
  121. string input = Console.ReadLine();
  122. if (!input.Contains(':'))
  123. {
  124. Console.WriteLine("IPEndPoint in bad format");
  125. break;
  126. }
  127. string[] s1 = input.Split(':');
  128. IPAddress ipaddr;
  129. if (!IPAddress.TryParse(s1[0], out ipaddr) || !int.TryParse(s1[1], out port))
  130. {
  131. Console.WriteLine("IPEndPoint in bad format");
  132. Console.ReadLine();
  133. error = true;
  134. break;
  135. }
  136. ipep = new IPEndPoint(ipaddr, port);
  137. try
  138. {
  139. client = new TcpClient();
  140. client.Connect(ipep);
  141. }
  142. catch (Exception ex)
  143. {
  144. Console.WriteLine("Unable to connect\r\nReason: {0}", ex.Message);
  145. Console.ReadLine();
  146. error = true;
  147. }
  148. break;
  149. }
  150. while (!error)
  151. {
  152. Console.Clear();
  153. Console.WriteLine("File path: ");
  154. string filePath = Console.ReadLine();
  155. if (File.Exists(filePath) == false)
  156. {
  157. Console.WriteLine("File does not exist\r\nPress ENTER to try again");
  158. Console.ReadLine();
  159. }
  160. byte[] buffer;
  161. using (var fs = File.OpenRead(filePath))
  162. {
  163. buffer = new byte[fs.Length];
  164. fs.Read(buffer, 0, buffer.Length);
  165. fs.Close();
  166. }
  167. if (SendData(buffer))
  168. {
  169. Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));
  170. Console.ReadLine();
  171. }
  172. break;
  173. }
  174. }
  175. private bool SendData(byte[] data)
  176. {
  177. try
  178. {
  179. using (NetworkStream ns = client.GetStream())
  180. {
  181. ns.Write(data, 0, data.Length);
  182. ns.Close();
  183. }
  184. return true;
  185. }
  186. catch (Exception ex)
  187. {
  188. Console.WriteLine("Unable to send file\r\nReason: {0}\r\nDetailed:\r\n{1}", ex.Message, ex.ToString());
  189. Console.ReadLine();
  190. return false;
  191. }
  192. }
  193. }
  194. }
  195. }

comments powered by Disqus