Question

My Server Class:

namespace Net_Send_File
{
    class Server
    {


        private TcpListener listener;
        private IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 15550);
        private bool active;
        string  arg;
       // private Socket xxx;

        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.BackgroundColor = ConsoleColor.Green;
                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();
            // I tried this byte[] buffer = new byte[c.ReceiveBufferSize]; It throws an Exeption. 
            byte[] buffer = new byte[1024];

            int bytesRead;

            while (active)
            {
                bytesRead = 0;

                try
                {

                        bytesRead = s.Read(buffer, 0, buffer.Length/2);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Socket error @ {0}:\r\n{1}", ipaddr, ex.Message);
                    Console.ReadLine();
                    break;
                }

                if (bytesRead == 0)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine("Disconnected @ {0}", ipaddr);
                    //new Thread(new ParameterizedThreadStart.ListenForConnections);
                    break;
                }

                string dataStr = Encoding.ASCII.GetString(buffer, 0, buffer.Length);

                using (var fs = File.OpenWrite("test.txt"))
                {
                    fs.Write(buffer, 0, buffer.Length);
                    fs.Close();
                }
            }
        }

        private string TCPIP(TcpClient c)
        {
            return ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
        }

    };

My Client Class:

        class Client
    {
        private TcpClient client;
       // private TcpClient client1;
        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);
                    Console.WriteLine("client 1 is Ready!");

                    //client1 = new TcpClient();
                    //client1.Connect(ipep);
                    //Console.WriteLine("client 2 is Ready!");
                }
                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);
                    Int64 a = client.SendBufferSize; ;
                    fs.Close();
                }

                if (SendData(buffer))
                {
               // client.SendBufferSize(buffer);

                    //int a = client.SendBufferSize; ;

                    Console.WriteLine("File sent\r\nFile size: {0} KB", (buffer.Length / 1024));


                    //a.SetLength((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;
            }
        }
    }

}
}

First of all accept my apologise for my code is badly commented. Or to be honest no comments at all, almost.

Server class, under the method called private void HandleClient Data(object _) I have a buffer. Buffer is set to byte[1024]. I want to receive bufferSize (of my test file) from client, set Server buffer = to ClientBuffer and there after receive file. I have a test file which is 60MB. I tried to send my buffer size from client to server but it doesn't work well. Can someone tell me what I can do and how?

thanks in advance

Was it helpful?

Solution

You should implement an application level protocol, for example:

MESSAGE:
    [SIZE (8 BYTES)][DATA (SIZE BYTES)]

Then, use BinaryReader and BinaryWriter

//client
var writer = new BinaryWriter(client.GetStream());
FileInfo fileInfoToSend = new FileInfo(path);
long fileSize = fileInfoToSend.Length;
writer.Write(fileSize);
using (FileStream fileStream = fileInfoToSend .Open(FileMode.Open, FileAccess.Read)) 
{    
    fileStream.CopyTo(writer.BaseStream);
    fileStream.Close();
}

//server
var stream = c.GetStream();
var reader = new BinaryReader(c.GetStream());
FileInfo fileInfoToWrite = new FileInfo(path);
long fileSize = reader.ReadInt64();
using (FileStream fileStream = fileInfoToWrite.Create()) 
{    
    int read = 0;
    for (long i = 0; i < fileSize; i += (long)read)
    {
       byte[] buffer = new byte[1024];
       read = stream.Read(buffer, 0, Math.Min(fileSize - i, 1024));
       if (read == 0)
          return;//client disconnected!(or throw Exception)
       fileStream.Write(buffer, 0, read);
    }
}

untested

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top