Advertisement
benshepherd

C# Send file over TCP

Feb 6th, 2013
1,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.95 KB | None | 0 0
  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.  
  10. namespace Net_Send_File
  11. {
  12.     class Program
  13.     {
  14.         static string input;
  15.         static void Main(string[] args)
  16.         {
  17.             while (true)
  18.             {
  19.                 Console.Clear();
  20.                 Console.Title = "Main menu";
  21.  
  22.                 Console.WriteLine("[1] Use as server");
  23.                 Console.WriteLine("[2] Use as client");
  24.                 input = Console.ReadLine();
  25.  
  26.                 if (input.Length == 0)
  27.                     continue;
  28.                 else if (input[0] == '1')
  29.                     new Server();
  30.                 else if (input[0] == '2')
  31.                     new Client();
  32.                 else
  33.                     continue;
  34.                    
  35.             }
  36.         }
  37.  
  38.         class Server
  39.         {
  40.             private TcpListener listener;
  41.             private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8000);
  42.             private bool active;
  43.  
  44.             public Server()
  45.             {
  46.                 Console.Clear();
  47.                 Console.Title = "Server";
  48.                 Main();
  49.             }
  50.  
  51.             private void Main()
  52.             {
  53.                 listener = new TcpListener(ipep);
  54.  
  55.                 try
  56.                 {
  57.                     listener.Start();
  58.                     active = true;
  59.  
  60.                     ListenForConnections();
  61.                 }
  62.                 catch (Exception ex)
  63.                 {
  64.                     Console.WriteLine(ex.Message);
  65.                     Console.ReadLine();
  66.                 }
  67.             }
  68.  
  69.             private void ListenForConnections()
  70.             {
  71.                 Console.Clear();
  72.                 Console.WriteLine("Listening for connections...");
  73.  
  74.                 while (active)
  75.                 {
  76.                     TcpClient client = listener.AcceptTcpClient();
  77.  
  78.                     Console.WriteLine("Connection @ {0}", TCPIP(client));
  79.  
  80.                     new Thread(new ParameterizedThreadStart(HandleClientData)).Start(client);
  81.                 }
  82.             }
  83.  
  84.             private void HandleClientData(object _c)
  85.             {
  86.                 TcpClient c = (TcpClient)_c;
  87.                 string ipaddr = TCPIP(c);
  88.  
  89.                 NetworkStream s = c.GetStream();
  90.                 byte[] buffer = new byte[1024 * 10];
  91.                 int bytesRead;
  92.  
  93.                 while (active)
  94.                 {
  95.                     bytesRead = 0;
  96.  
  97.                     try
  98.                     {
  99.                         bytesRead = s.Read(buffer, 0, buffer.Length);
  100.                     }
  101.                     catch (Exception ex)
  102.                     {
  103.                         Console.WriteLine("Socket error @ {0}:\r\n{1}", ipaddr, ex.Message);
  104.                         Console.ReadLine();
  105.                         break;
  106.                     }
  107.  
  108.                     if (bytesRead == 0)
  109.                     {
  110.                         Console.WriteLine("Disconnected @ {0}", ipaddr);
  111.                         break;
  112.                     }
  113.  
  114.                     string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
  115.  
  116.                     using (var fs = File.OpenWrite("recieved.jpg"))
  117.                     {
  118.                         fs.Write(buffer, 0, buffer.Length);
  119.                         fs.Close();
  120.                     }
  121.                 }
  122.             }
  123.  
  124.             private string TCPIP(TcpClient c)
  125.             {
  126.                 return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
  127.             }
  128.         }
  129.  
  130.         class Client
  131.         {
  132.             private TcpClient client;
  133.             private IPEndPoint ipep;
  134.             private int port;
  135.  
  136.             public Client()
  137.             {
  138.                 Console.Clear();
  139.                 Console.Title = "Client";
  140.                 bool error = false;
  141.  
  142.                 while (true)
  143.                 {
  144.                     Console.WriteLine("IPEndPoint: ");
  145.                     string input = Console.ReadLine();
  146.  
  147.                     if (!input.Contains(':'))
  148.                     {
  149.                         Console.WriteLine("IPEndPoint in bad format");
  150.                         break;
  151.                     }
  152.  
  153.                     string[] s1 = input.Split(':');
  154.                     IPAddress ipaddr;
  155.  
  156.                     if (!IPAddress.TryParse(s1[0], out ipaddr) || !int.TryParse(s1[1], out port))
  157.                     {
  158.                         Console.WriteLine("IPEndPoint in bad format");
  159.                         Console.ReadLine();
  160.                         error = true;
  161.                         break;
  162.                     }
  163.  
  164.                     ipep = new IPEndPoint(ipaddr, port);
  165.  
  166.                     try
  167.                     {
  168.                         client = new TcpClient();
  169.                         client.Connect(ipep);
  170.                     }
  171.                     catch (Exception ex)
  172.                     {
  173.                         Console.WriteLine("Unable to connect\r\nReason: {0}", ex.Message);
  174.                         Console.ReadLine();
  175.                         error = true;
  176.                     }
  177.  
  178.                     break;
  179.                 }
  180.  
  181.                 while (!error)
  182.                 {
  183.                     Console.Clear();
  184.                     Console.WriteLine("File path: ");
  185.                     string filePath = Console.ReadLine();
  186.  
  187.                     if (File.Exists(filePath) == false)
  188.                     {
  189.                         Console.WriteLine("File does not exist\r\nPress ENTER to try again");
  190.                         Console.ReadLine();
  191.                     }
  192.  
  193.                     byte[] buffer;
  194.                     using (var fs = File.OpenRead(filePath))
  195.                     {
  196.                         buffer = new byte[fs.Length];
  197.                         fs.Read(buffer, 0, buffer.Length);
  198.                         fs.Close();
  199.                     }
  200.  
  201.                     if (SendData(buffer))
  202.                     {
  203.                         Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));
  204.                         Console.ReadLine();
  205.                     }
  206.  
  207.                     break;
  208.                 }
  209.             }
  210.  
  211.             private bool SendData(byte[] data)
  212.             {
  213.                 try
  214.                 {
  215.                     using (NetworkStream ns = client.GetStream())
  216.                     {
  217.                         ns.Write(data, 0, data.Length);
  218.                         ns.Close();
  219.                     }
  220.  
  221.                     return true;
  222.                 }
  223.                 catch (Exception ex)
  224.                 {
  225.                     Console.WriteLine("Unable to send file\r\nReason: {0}\r\nDetailed:\r\n{1}", ex.Message, ex.ToString());
  226.                     Console.ReadLine();
  227.  
  228.                     return false;
  229.                 }
  230.             }
  231.         }
  232.     }
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement