benshepherd icon

C# Send file over TCP

benshepherd | PRO | 02/06/13 09:43:07 PM UTC | 0 ⭐ | 1308 👁️ | Never ⏰ | []
C# |

6.95 KB

|

None

|

0 👍

/

0 👎

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
 
namespace Net_Send_File
{
    class Program
    {
        static string input;
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Clear();
                Console.Title = "Main menu";
 
                Console.WriteLine("[1] Use as server");
                Console.WriteLine("[2] Use as client");
                input = Console.ReadLine();
 
                if (input.Length == 0)
                    continue;
                else if (input[0] == '1')
                    new Server();
                else if (input[0] == '2')
                    new Client();
                else
                    continue;
                    
            }
        }
 
        class Server
        {
            private TcpListener listener;
            private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8000);
            private bool active;
 
            public Server()
            {
                Console.Clear();
                Console.Title = "Server";
                Main();
            }
 
            private void Main()
            {
                listener = new TcpListener(ipep);
 
                try
                {
                    listener.Start();
                    active = true;
 
                    ListenForConnections();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadLine();
                }
            }
 
            private void ListenForConnections()
            {
                Console.Clear();
                Console.WriteLine("Listening for connections...");
 
                while (active)
                {
                    TcpClient client = listener.AcceptTcpClient();
 
                    Console.WriteLine("Connection @ {0}", TCPIP(client));
 
                    new Thread(new ParameterizedThreadStart(HandleClientData)).Start(client);
                }
            }
 
            private void HandleClientData(object _c)
            {
                TcpClient c = (TcpClient)_c;
                string ipaddr = TCPIP(c);
 
                NetworkStream s = c.GetStream();
                byte[] buffer = new byte[1024 * 10];
                int bytesRead;
 
                while (active)
                {
                    bytesRead = 0;
 
                    try
                    {
                        bytesRead = s.Read(buffer, 0, buffer.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Socket error @ {0}:\r\n{1}", ipaddr, ex.Message);
                        Console.ReadLine();
                        break;
                    }
 
                    if (bytesRead == 0)
                    {
                        Console.WriteLine("Disconnected @ {0}", ipaddr);
                        break;
                    }
 
                    string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
 
                    using (var fs = File.OpenWrite("recieved.jpg"))
                    {
                        fs.Write(buffer, 0, buffer.Length);
                        fs.Close();
                    }
                }
            }
 
            private string TCPIP(TcpClient c)
            {
                return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
            }
        }
 
        class Client
        {
            private TcpClient client;
            private IPEndPoint ipep;
            private int port;
 
            public Client()
            {
                Console.Clear();
                Console.Title = "Client";
                bool error = false;
 
                while (true)
                {
                    Console.WriteLine("IPEndPoint: ");
                    string input = Console.ReadLine();
 
                    if (!input.Contains(':'))
                    {
                        Console.WriteLine("IPEndPoint in bad format");
                        break;
                    }
 
                    string[] s1 = input.Split(':');
                    IPAddress ipaddr;
 
                    if (!IPAddress.TryParse(s1[0], out ipaddr) || !int.TryParse(s1[1], out port))
                    {
                        Console.WriteLine("IPEndPoint in bad format");
                        Console.ReadLine();
                        error = true;
                        break;
                    }
 
                    ipep = new IPEndPoint(ipaddr, port);
 
                    try
                    {
                        client = new TcpClient();
                        client.Connect(ipep);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to connect\r\nReason: {0}", ex.Message);
                        Console.ReadLine();
                        error = true;
                    }
 
                    break;
                }
 
                while (!error)
                {
                    Console.Clear();
                    Console.WriteLine("File path: ");
                    string filePath = Console.ReadLine();
 
                    if (File.Exists(filePath) == false)
                    {
                        Console.WriteLine("File does not exist\r\nPress ENTER to try again");
                        Console.ReadLine();
                    }
 
                    byte[] buffer;
                    using (var fs = File.OpenRead(filePath))
                    {
                        buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        fs.Close();
                    }
 
                    if (SendData(buffer))
                    {
                        Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));
                        Console.ReadLine();
                    }
 
                    break;
                }
            }
 
            private bool SendData(byte[] data)
            {
                try
                {
                    using (NetworkStream ns = client.GetStream())
                    {
                        ns.Write(data, 0, data.Length);
                        ns.Close();
                    }
 
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to send file\r\nReason: {0}\r\nDetailed:\r\n{1}", ex.Message, ex.ToString());
                    Console.ReadLine();
 
                    return false;
                }
            }
        }
    }
}

Comments