Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#C#4.0
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)
        {
 
        }
    }
Posted 23-Nov-12 4:57am
Edited 23-Nov-12 4:58am
v2
Comments
digimanus at 23-Nov-12 11:03am
   
you obviously create a memorystream while sending via a FileStream object can do the job.
Richard MacCutchan at 23-Nov-12 11:44am
   
If you are going to read the entire file into memory then you are bound to have problems with huge files. Read smaller blocks and transfer one block at a time.

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Sending File {NO Limit}
Client Code
/******************************************************************************************
 Author						: Sunil S. Bhambhani
 Created					: 27th June 2003
 Last Modified				: 23rd August 2003
 Language					: C#
 
 Summary: This Program is all about how to get file from other computer on local network
 with the help of another program named as "newftpServer_1.1". This program shows you
 basicaly the concept of how to transfer file from on computer to anothercomputer
 with the help of sockets and filestreambuffers.
******************************************************************************************/
//all required header files
using System;
using System.IO;
using System.Net.Sockets;
using System.Net;
 
//declearing class
class FtpClient
{	
	public  static void Main()
	{
		Console.WriteLine("\n\n                 WelCome to Sunil's FTP. Client\n\n");
		Console.Write("\n Create a folder in (C) drive named as \"ftpService\" in which the files will-\n be downloaded from the Server.\n\n");
		Console.Write(" Enter IP Address of Computer Where Server is Running: ");
		string ipaddr=Console.ReadLine();		
		Console.Write("\n\n Enter File Name or Path use this(/) slash for path: \n ");
		string fname=Console.ReadLine();
		
		//creating object of TcpClient to catch the stream of connected computer
		TcpClient Server=null;			
		try
		{	
			IPAddress myIP = IPAddress.Parse(ipaddr);
			//sending the computer IPAddress and port number on the network			
			
			IPHostEntry entry=Dns.GetHostByAddress(myIP);
			
				Server = new TcpClient(entry.HostName,3099);			
			
		}
		catch(Exception)
		{
			Console.WriteLine("\n\n    Server Not found Enter Correct Machine Name");
			return;
			
		}
		//getting the networkserver stream object
		NetworkStream serverstream=Server.GetStream();		
		//creating streamreader object to read messages from server
		StreamReader reader=new StreamReader(serverstream);
		//creating streamwriter object to send messages to server
		StreamWriter writer=new StreamWriter(serverstream);				
		writer.AutoFlush=true;			
		//sending file name to server 
		writer.WriteLine(fname);
		
		string name="c:\\ftpService\\";
		string temp=null;
		//reading the message from server that file found or filename
		string name1=reader.ReadLine();
		if(name1=="File not found")
		{
			Console.WriteLine("\n\n    File not found");			
			writer.Close();
			reader.Close();
			return;
		}		
		//logic of extracting file name from the given path
		for(int i=name1.Length;i>=1;i--)
		{
			char c=name1[i-1];
			if(c=='/') break;
			temp+=c;
		}
		//setting the path for opening file at the client side like "c:\ftpService\xyz.cs"
		for(int i=temp.Length;i>=1;i--)
		{
			char c=temp[i-1];			
			name+=c;
		}
		
	
		Stream destinationfilestream;		
		try
		{
			//getting the file stream of destinationfile
			destinationfilestream=File.OpenWrite(name);
 
		}
		catch
		{
			
			Console.WriteLine("\n\n      Please Create a folder in (C) drive named as \"ftpService\" ");
			writer.WriteLine("File not found");
			serverstream.Close();
			return; 
		}
 
		
		const int buffsize=1024;
		try
		{			
			/*creating the bufferedstrem object for reading 1024 size of bytes from the 
			  server stream   */
			BufferedStream bufferedinput=new BufferedStream(serverstream);	
 
			/*creating the bufferedstrem object for write bytes which are read 
			  from server   */ 									
			BufferedStream bufferedoutput=new BufferedStream(destinationfilestream);
			int bytesread;	
			/* creating array of bytes size is 1024 */		
			byte[] buffer=new Byte[buffsize];	
			
			/* Reading bytes from the server until the end */
			while((bytesread=bufferedinput.Read(buffer,0,buffsize))>0)		
			{
				/* writing the bytes in the destination file*/
				bufferedoutput.Write(buffer,0,bytesread);
			}
 
			Console.WriteLine("\n\n    file copied in {0}",name);
			
			/* flushing the last buffer bytes from RAM*/
			bufferedoutput.Flush();
 
			/* Closing connections*/
			bufferedinput.Close();
			bufferedoutput.Close();
			Console.WriteLine("\n\n  Press Enter.....");
			Console.ReadLine();
 
			
			
			
		}
		catch(Exception)
		{
			Console.WriteLine("\n\n    Please check you harddisk space or someone shutdown the server");			
			writer.Close();
			reader.Close();			
		}
 
		/* Closing Connections*/
		reader.Close();
		writer.Close();
				
	}
	
}
 
Sever Code
/******************************************************************************************
 Author						: Sunil S. Bhambhani
 Created					: 27th June 2003
 Last Modified				: 23rd August 2003
 Language					: C#
 
 Summary: This Program is all about how to get file from other computer on local network
 with the help of another program named as "newftpClient_1.1". This program shows you
 basicaly the concept of how to transfer file from on computer to anothercomputer
 with the help of sockets and filestreambuffers.
******************************************************************************************/
 
//all required header files
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
 
class FtpServer
{
	public static void Main()
	{
		/* Creating Port no 3099 on server for listening the client request*/
		TcpListener listener=new TcpListener(3099);
		Console.WriteLine("        Welcome to Sunil's FTP. Server");
		Console.WriteLine("\n Server Starts and Listening on Port(3099)....");
 
		/* start listening for any request*/
		listener.Start();
 
		/* calling function Service*/
		Service(listener);
 
	}
 
	public static void Service(TcpListener server)
	{
		while(true)
		{
			//creating object of TcpClient to catch the stream of connected computer
			TcpClient client=server.AcceptTcpClient();
 
			//getting the networkclient stream object
			NetworkStream clientstream=client.GetStream();
 
			//creating streamreader object to read messages from client
			StreamReader reader=new StreamReader(clientstream);
 
			//creating streamwriter object to send messages to client
			StreamWriter writer=new StreamWriter(clientstream);			
 
			writer.AutoFlush=true;		
		// reading file name from client
			string sourcefile=reader.ReadLine();			
			
			Stream inputstream;
			try
			{
				//opening file in read mode
				inputstream=File.OpenRead(sourcefile);
 
				//sending file name to the client
				writer.WriteLine(sourcefile);
 
			}
			catch
			{
				Console.WriteLine("\n\n  File not found named: {0}",sourcefile);
 
				//sending message to client if file not found
				writer.WriteLine("File not found");
				clientstream.Close();
				continue;
			}
			const int sizebuff=1024;
			try
				{
				/*creating the bufferedstrem object for reading 1024 size of bytes from the 
					file */ 
					BufferedStream bufferedinput=new BufferedStream(inputstream);								
 
				/*creating the bufferedstrem object for sending bytes which are read 
					from file   */ 	
					BufferedStream bufferedoutput=new BufferedStream(clientstream);
 
					/* creating array of bytes size is 1024 */	
					byte[] buffer=new Byte[sizebuff];					
					int bytesread;					
					
					/* Reading bytes from the file until the end */
					while((bytesread=bufferedinput.Read(buffer,0,sizebuff))>0)
					{	
						/* sending the bytes to the client */
						bufferedoutput.Write(buffer,0,bytesread);								
					}
					Console.WriteLine("\n\n    file copied name:{0}",sourcefile);
 
					/* Closing connections*/
					bufferedoutput.Flush();
					bufferedinput.Close();
					bufferedoutput.Close();
				}				
				catch(Exception)
				{
					Console.WriteLine("\n\n Connection Couldnot Esablished  because Client forget to create-\n \"ftpService\" folder in his (C) Drive or his/her harddisk is full or Client close its Connection in between process");																						
					writer.Close();
					reader.Close();
					continue;
				}
			/* Closing connections*/			
			writer.Close();
			reader.Close();
 
		}
	}
}
  Permalink  
Comments
Emily Alice at 30-Nov-12 9:42am
   
Oh it is FTP Program, my program is only send and recieve large file between 2 PC in LAN network, but thank very much for help, so what is a destination when I send a file and I can run demo program client and program server in the same PC ? Can or Can't ?: example as I want to sent file Win2K3SP2.iso (about 700M) it located in E:\folder\Win2K3.iso what I have to do next ? or you can show some picture of demo for me to see it. One thing importance that I want to say is I hearing that some people say should used chunks method to send a recieve a large file ? it is safety and perfect. Who can give me something about chunk ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Guruprasad.K.Basavaraju 450
1 Sergey Alexandrovich Kryukov 325
2 Shai Vashdi 318
3 OriginalGriff 265
4 Peter Leow 171
0 Sergey Alexandrovich Kryukov 9,109
1 OriginalGriff 5,290
2 Peter Leow 4,010
3 Maciej Los 3,535
4 Abhinav S 3,263


Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 6 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid