0
Answer

[Socket C#]Program about send and recieve a large file.

Maria Bili

Maria Bili

11y
8.1k
1
I have a homework Network Programming C# is write a bout send & recieve a large file (a file as large as better, may be > 1G) so I have reference in internet a write a program to reference here, I happy that it send a large file >100M) so sometime I send a file a bout 500M it fail an notify that: OutOfMemoryException was Unhandle. Exception of type "System.OutOfMemoryException" was thrown. Please fix it for me and give me some advice or instruction to do it better.

Picture of Client:
http://i1055.photobucket.com/albums/s505/vn_photo/22-1.jpg

Picture of Server:
http://i1055.photobucket.com/albums/s505/vn_photo/11-2.jpg

Picture Fail:
http://i1055.photobucket.com/albums/s505/vn_photo/33-2.jpg

Code of Client:
    public partial class Form1 : Form
    {
        string splitter = "'\\'";
        string fName;
        string[] split = null;
        byte[] clientData;

                public Form1()
        {
            InitializeComponent();
            button2.Visible = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            char[] delimiter = splitter.ToCharArray();
            //openFileDialog1.ShowDialog();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
                textBox2.AppendText("Selected file " + textBox1.Text);
                button2.Visible = true;
            }
            else
            {
                textBox2.AppendText("Please Select any one file to send");
                button2.Visible = false;
            }

            split = textBox1.Text.Split(delimiter);
            int limit = split.Length;
            fName = split[limit - 1].ToString();
            if (textBox1.Text != null)
                button1.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //IPAddress ip = new IPAddress;


            byte[] fileName = Encoding.UTF8.GetBytes(fName); //file name
            byte[] fileData = File.ReadAllBytes(textBox1.Text); //file
            byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //lenght of file name
            clientData = new byte[4 + fileName.Length + fileData.Length];

            fileNameLen.CopyTo(clientData, 0);
            fileName.CopyTo(clientData, 4);
            fileData.CopyTo(clientData, 4 + fileName.Length);

            textBox2.AppendText("Preparing File To Send");
            clientSock.Connect("127.0.0.1", 9050); //target machine's ip address and the port number
            clientSock.Send(clientData);
            //clientSock.
            clientSock.Close();
        }
    }

Code of Server:
    public partial class Form1 : Form
    {
        Thread t1;
        int flag = 0;
        string receivedPath = "yok";
        public delegate void MyDelegate();
        private string fileName;
        public Form1()
        {
            t1 = new Thread(new ThreadStart(StartListening));
            t1.Start();
            InitializeComponent();
        }


        public class StateObject
        {
            // Client socket.
            public Socket workSocket = null;

            public const int BufferSize = 8096;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
        }

        public static ManualResetEvent allDone = new ManualResetEvent(true);

        public void StartListening()
        {
            byte[] bytes = new Byte[8096];
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                listener.Bind(ipEnd);
                listener.Listen(100);
                //SetText("Listening For Connection");//.net framework 4.5
                while (true)
                {
                    allDone.Reset();
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    allDone.WaitOne();

                }
            }
            catch (Exception ex)
            {
            }

        }

        public void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set();

            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
            flag = 0;

        }

        public void ReadCallback(IAsyncResult ar)
        {
            int fileNameLen = 1;
            String content = String.Empty;
            StateObject state = (StateObject)ar.AsyncState;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {
                if (flag == 0)
                {
                    fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                    fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                    receivedPath = @"C:\" + fileName;
                    flag++;
                }

                if (flag >= 1)
                {
                    BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                    if (flag == 1)
                    {
                        writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                        flag++;
                    }
                    else
                        writer.Write(state.buffer, 0, bytesRead);
                    writer.Close();
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
            }
            else
            {
                Invoke(new MyDelegate(LabelWriter));
            }

        }
        public void LabelWriter()
        {
            label1.Text = "Data has been received " + fileName;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            t1.Abort();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }